2015-08-21 103 views
0

我有DataGridView和DataTable,DataTable在DataGridView中作爲數據源分配。Winform C#在DataTable上更新DataGridView單元格值已更改

當我更改DataTable中的某些值時,它不會在視圖上更新。

所以,我怎樣才能實現這一目標

我曾嘗試下面的事情

  1. 的BindingSource
  2. 刷新()

演示代碼

DataGridView datagrid = new DataGridView(); 
DataTable dt = new DataTable(); 

dt.Columns.Add("No"); 
dt.Columns.Add("Name"); 

for (int i = 1; i <= 10; i++) 
{ 
    DataRow row = dt.NewRow(); 
    row[0] = i; 
    row[1] = "ABC"; 
    dt.Rows.Add(row); 
} 

datagrid.DataSource = dt; 

這裏米Ÿ上面的代碼

當我改變DataTable中一些價值它不是在DataGridView中反映

dt.Rows[0][1] = "XYZ"; 

所以請幫助我....

+0

在什麼情況下,你改變了價值? – thewisegod

+0

@thewisegod一些按鈕單擊事件我改變數據表中的值 –

+0

如何從click事件中獲取對數據表的引用?數據表是在頁面級聲明的嗎? – thewisegod

回答

1

我能夠做到這一點,它的工作原理:

private DataTable _dt = new DataTable(); 

private void Form1_Load(object sender, EventArgs e) 
{ 

    _dt.Columns.Add("LongText"); 
    DataRow dr = _dt.NewRow(); 
    dr[0] = "One"; 
    _dt.Rows.Add(dr); 
    dr = _dt.NewRow(); 
    dr[0] = "Two"; 
    _dt.Rows.Add(dr); 
    dr = _dt.NewRow(); 
    dr[0] = "Three"; 
    _dt.Rows.Add(dr); 
    dataGridView1.DataSource = _dt; 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    _dt.Rows[0][0] = "daddy"; 
} 
+0

是的,我想這樣做,但是不知道爲什麼它不適用於我 –

+0

那麼您的代碼是如何設置的?如果那是絕對不可思議的。 – thewisegod

+0

請DatagridView數據源設置部分在按鈕單擊事件..然後它正在工作? –

1

您需要將您的數據網格添加到您的形式,像這樣:

private void Form1_Load(object sender, EventArgs e) 
    { 
     DataGridView datagrid = new DataGridView(); 

     DataTable dt = new DataTable(); 

     //add this line 
     Controls.Add(datagrid); 

     dt.Columns.Add("No"); 
     dt.Columns.Add("Name"); 

     for (int i = 1; i <= 10; i++) 
     { 
      DataRow row = dt.NewRow(); 
      row[0] = i; 
      row[1] = "ABC"; 
      dt.Rows.Add(row); 
     } 

     datagrid.DataSource = dt; 

     dt.Rows[0][1] = "XYZ"; 
    } 

結果:

enter image description here

+0

我通過設計師 –

+0

將datagridview添加到表單中,但是您的代碼顯示的是代碼後面創建的數據網格,而不是通過設計器:'DataGridView datagrid = new DataGridView();' – jsanalytics

相關問題