【问题标题】:DataGridView sample binding issueDataGridView 示例绑定问题
【发布时间】:2010-10-08 09:08:18
【问题描述】:

我需要在表格中添加一个变量对列表(名称-值)。我决定将它设置在 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 列,名称和值是自动生成的,并且网格是空的。

但是当我点击添加参数按钮时,什么都没有发生……错误在哪里?

【问题讨论】:

    标签: .net winforms data-binding datagridview


    【解决方案1】:
    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);
            }
        }
    

    【讨论】:

    • 啊……我的错。我习惯了 WebForm 的 DataBind()。您需要 BindingSource 才能使其工作。我已经编辑了我的帖子。我很抱歉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多