2010-10-08 98 views
1

我需要在窗體(名稱 - 值)中添加一個變量對列表。我決定把它在一個DataGridView,並且使用簡單的暴食來管理它(.NET 2):DataGridView示例綁定問題

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
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); 
     } 
    } 
+0

ahh ..我的不好。我習慣了WebForm的DataBind()。你需要BindingSource來使它工作。我編輯了我的帖子。我的道歉。 – bla 2010-10-08 09:29:22

+0

很酷。我甚至不需要添加按鈕... – serhio 2010-10-08 09:41:21