1. 程式人生 > >c# datagridview繫結資料來源(BindingList<class>)中的現象 待查

c# datagridview繫結資料來源(BindingList<class>)中的現象 待查

現象1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace datagridview
{
    public partial class Form1 : Form
    {
        public Int32 count = 0;
        public string str = "test!";
        BindingList<Item> items = new BindingList<Item>();

        public Form1()
        {
            InitializeComponent();

            //禁止自動建立列
            this.dataGridView1.AutoGenerateColumns = false;

            //將左邊的一欄去掉
            this.dataGridView1.RowHeadersVisible = false;

            //允許使用者交換列
            this.dataGridView1.AllowUserToOrderColumns = true;

            this.dataGridView1.DataSource = items;

            //建立“序號”列
            DataGridViewTextBoxColumn serial = new DataGridViewTextBoxColumn();
            serial.HeaderText = "序號";
            serial.DataPropertyName = "Serial";
            this.dataGridView1.Columns.Add(serial);

            //建立“文字”列
            DataGridViewTextBoxColumn text = new DataGridViewTextBoxColumn();
            text.HeaderText = "文字";
            text.DataPropertyName = "Text";
            this.dataGridView1.Columns.Add(text);
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
        }

        private void button2_Click(object sender, EventArgs e)
        {
            items.Add(new Item(str, count++));
            //items.Add(new Item(0) { Text = str, Serial = count++ });

            //有時候使用DataGridView難免會在最後插入一條資料,如果插入的資料超過滾動條顯示的行數,
            //那麼預設情況下不會顯示到最後一行。增加以下程式碼一直將滾動條拉倒最低。
            this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count - 1;
        }
    }

    class Item
    {
        private string _text;
        private int _serial;

        public string Text
        {
            get { return _text; }
        }

        public int Serial
        {
            get { return _serial; }
        }

        public Item(string text, int serial)
        {
            this._text = text;
            this._serial = serial;
        }

        //public string Text { get; set; }

        //public int Serial { get; set; }

        //public Item(int serial)
        //{
        //    int a = 0;
        //}
    }
}

執行結果:

當在Item類中增加預設建構函式後:

    class Item
    {
        private string _text;
        private int _serial;

        public string Text
        {
            get { return _text; }
        }

        public int Serial
        {
            get { return _serial; }
        }

        public Item(string text, int serial)
        {
            this._text = text;
            this._serial = serial;
        }

        public Item()
        {
            int a = 0;
        }

執行結果:

顯示最後一欄空白,原因未知待查!