简体   繁体   English

绑定后更改Datagridview中的值

[英]change values in Datagridview when it has been binded

In my project, I am trying to change values in a column of DataGridView after binding it with DataSet. 在我的项目中,我尝试将其与DataSet绑定后更改DataGridView列中的值。 Something like this: 像这样:

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)
        }
    }                            
 }

My solution is entering in to the if statement successfully and even txt holds correct value but I dont know what is happening at r.Cells[4] that it has the same old previous value. 我的解决方案是成功输入if语句,甚至txt具有正确的值,但是我不知道r.Cells[4]发生了什么,它具有相同的旧值。
Everything is correct eventhough the value in the grid columns are not changing.. How to change them? 尽管网格列中的值没有更改,但一切都正确。如何更改它们?

You need to use CellFormatting event of DataGridView : 您需要使用DataGridView CellFormatting事件:

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();
             }
         }
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM