winForms + DataGridView绑定到List <t>(Visual Studio 2005,C#2.0)</t>

时间:2012-01-11 07:57:19

标签: datagridview c#-2.0

我有以下代码,但DatGridView显示空行。我找不到解决方案。我已将AutoGenerateColumns设置为false。如果我将其设置为true,则会创建行,但我不允许将此属性设置为true(客户端希望)。

我做错了什么?这是代码:

public partial class Form1 : Form
{
    private List<AStruct> _aCollectionList;
    private BindingList<AStruct> _aCollectionBindingList;

    public struct AStruct
    {
        public string ACode
        {
            get { return _aCode; }
            set { _aCode = value; }
        }

        public string AName
        {
            get { return _aName; }
            set { _aName = value; }
        }

        private string _aCode;
        private string _aName;
    }

    public Form1()
    {
        InitializeComponent();
        this.dataGridView1.AutoGenerateColumns = false;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _aCollectionList = new List<AStruct>();
        FillCollectionStruct(true);

        dataGridView1.DataSource = _aList;
        dataGridView1.Refresh();            
    }

    private void button2_Click(object sender, EventArgs e)
    {            
        _aCollectionBindingList = new BindingList<AStruct>();
        FillCollectionStruct(false);
        dataGridView1.DataSource = _aBindingList;
        dataGridView1.Refresh();         
    }

    private void FillCollectionStruct(bool listBool)
    {
        AStruct aStruct = new AStruct();

        for (int i = 0; i < 10; i++)
        {
            aStruct.ACode = i.ToString();
            aStruct.AName = i.ToString();

            if (listBool)
                _aCollectionList.Add(aStruct);
            else
                _aCollectionBindingList.Add(aStruct);
        }
    }
}

在Form1.Designer中,我做了以下列:

// 
// aCodeColumn
// 
this.colorCodeColumn.DataPropertyName = "Code";
this.colorCodeColumn.HeaderText = "a code";
this.colorCodeColumn.Name = "aCodeColumn";
// 
// aNameColumn
// 
this.colorNameColumn.DataPropertyName = "Name";
this.colorNameColumn.HeaderText = "a name";
this.colorNameColumn.Name = "aNameColumn";

2 个答案:

答案 0 :(得分:0)

你不能只改变绑定:

// aCodeColumn
// 
this.colorCodeColumn.DataPropertyName = "Code";
this.colorCodeColumn.HeaderText = "a code";
this.colorCodeColumn.Name = "aCodeColumn";
// 
// aNameColumn
// 
this.colorNameColumn.DataPropertyName = "Name";
this.colorNameColumn.HeaderText = "a name";
this.colorNameColumn.Name = "aNameColumn";

要:

// aCodeColumn
// 
this.colorCodeColumn.DataPropertyName = "ACode";
this.colorCodeColumn.HeaderText = "a code";
this.colorCodeColumn.Name = "aCodeColumn";
// 
// aNameColumn
// 
this.colorNameColumn.DataPropertyName = "AName";
this.colorNameColumn.HeaderText = "a name";
this.colorNameColumn.Name = "aNameColumn";

不应该这样吗?

由于DataPropertyName绑定到您的属性,因此名称必须相同,否则编译器无法知道其中的位置。

答案 1 :(得分:0)

如果我理解你的问题,你可以使用像这样的数据.dataGridView1.Refresh();为了重新填充它,在你刷新的行之前放入this.dataGridView1.DataSource = _aCollectionBindingList;