2012-11-14 41 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]是否有行吗? –

相关问题