2012-11-14 46 views
0

在我的項目中,我試圖在用DataSet綁定DataGridView的列時更改其值。事情是這樣的:Datagridview在綁定時更改值

dgvMain --> DataGridView 
dsMainPatients --> DataSet 
dsMainDoctors --> DataSet 

dgvMain.DataSource = null; 
    dgvMain.DataSource = dsMainPatients.Tables[0]; 

foreach (DataGridViewRow r in dgvMain.Rows) 
{ 
    DataGridViewTextBoxCell txt = new DataGridViewTextBoxCell(); 
    for (int intCount = 0; intCount < dsMainDoctors.Tables[0].Rows.Count; intCount++) 
    { 
     if (r.Cells[4].Value.ToString().Equals(dsMainDoctors.Tables[0].Rows[intCount][0].ToString())) 
     { 
      txt.Value = dsMainDoctors.Tables[0].Rows[intCount][1].ToString(); 
      r.Cells[4] = txt; //dgvMain[4, r.Index] = txt; (also tried) 
     } 
    }        
} 

我的解決方案成功地進入if語句,甚至txt持有正確的值,但我不知道什麼是在r.Cells[4]發生的事情,它具有與之前相同的舊值。
一切都是正確的,儘管網格列中的值沒有改變..如何改變它們?

回答

1

您需要使用CellFormatting事件的DataGridView

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if (e.ColumnIndex == 4) 
    { 
     for (int intCount = 0; intCount < dsMainDoctors.Tables[0].Rows.Count; intCount++) 
     { 
      if (e.Value.ToString().Equals(dsMainDoctors.Tables[0].Rows[intCount][0].ToString())) 
      { 
        e.Value = txt.Value = dsMainDoctors.Tables[0].Rows[intCount][1].ToString(); 
      } 
     } 
    } 
} 
+0

嘗試添加值單元格沒有這個for循環。刪除for循環,並在if語句中添加e.Value =「test」;結果是什麼 ? –

+0

嘿,對不起,這是因爲其他問題發生......現在問題是所有列都顯示'「DataGridViewTextBoxCell {ColumnIndex = -1,RowIndex = -1}」'。 –

+0

你可以調試應用程序,看看dsMainDoctors.Tables [0]是否有行嗎? –

相關問題