DataGridView示例绑定问题

时间:2010-10-08 09:08:19

标签: .net winforms data-binding datagridview

我需要在表单中添加变量对列表(Name-Value)。我决定在datagridview中设置它,并使用简单的binging来管理它(。NET 2 ):

public class EventParameter
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    private string value;

    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }
}

///////////////////// USER CONTROL INITIALIZATION
private List<EventParameter> eventGridParams;
public GridEventSender()
{
    InitializeComponent();
    eventGridParams = new List<EventParameter>();
    this.dataGridView1.AutoGenerateColumns = true;
    this.dataGridView1.DataSource = eventGridParams;
}

///////////////////// ADD PARAMETER BUTTON
private void btnAddParam_Click(object sender, EventArgs e)
{
    eventGridParams.Add(new EventParameter());
}

当我启动应用程序时,我看到自动生成2列,名称和值,并且网格为空。

但是当我点击添加参数按钮时,没有任何反应......错误在哪里?

1 个答案:

答案 0 :(得分:2)

public partial class frmGridView : Form
    {
        private List<EventParameter> eventGridParams;
        private BindingSource bs;
        public frmGridView()
        {
            InitializeComponent();
            eventGridParams = new List<EventParameter>();
            bs = new BindingSource();
            bs.DataSource = eventGridParams;
            //this.dataGridView1.AutoGenerateColumns = true;    //you don't need this
            this.dataGridView1.DataSource = bs;
        }

        private void button1_Click(object sender, EventArgs e)
        {
        //eventGridParams.Add(new EventParameter() { Name="a", Value = "a"});   //object initializer is only available for c# 3.0
        EventParameter eventParam = new EventParameter();
        eventParam.Name = "a";
        eventParam.Value = "a";
        eventGridParams.Add(eventParam);
        bs.ResetBindings(false);
        }
    }