现象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;
//}
}
}

运行结果:

c# datagridview绑定数据源(BindingList&lt;class&gt;)中的现象 待查-LMLPHP

当在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;
}

运行结果:

c# datagridview绑定数据源(BindingList&lt;class&gt;)中的现象 待查-LMLPHP

显示最后一栏空白,原因未知待查!

04-26 16:44