简体   繁体   中英

How to get Column name for a column value in a DataRow returned by GetChanges() method?

I have a datagridview based on four columns say with names A, B, C, D. Now, If I make changes in a row I can trap these changes using the following code:

DataTable DgvChangedDT = estDataSet.mat_comp_dtl_v.GetChanges();
try
{
   foreach (DataRow dr in DgvChangedDT.Rows)
   {
       Status = dr.RowState.ToString();
       if (Status == "Modified")
       {
           foreach (DataColumn dc in DgvChangedDT.Columns)
           {
              OrgVal = dr[dc, DataRowVersion.Original].ToString();
              CurrVal = dr[dc, DataRowVersion.Current].ToString();
              MessageBox.Show("Original Value: " + OrgVal + " ," + " Current Value: " +           CurrVal);
            }
          }
       }
    }
        catch (Exception ex)
        {
            MessageBox.Show("Exception: " + ex);
        }
    }

The Above code works fine and gives original and current values of column in DataSet in the order they appear in the DataSet. But my problem is that I want to get name of the column for the column value in each iteration which I want use to build my update statement to be sent to DataBase. It is required because the DataSet contains view instead of table and hence Visual Studio(2010) does not create Update method implicitly for the DataSet.

Can anyone suggest code for getting column name for each dc value in the second foreach loop?

GetChanges returns a DataTable with all changed rows. You're looping all columns of this table, so you have already all DataColumns . This has a ColumnName property which you are probably looking for.

// ...
foreach (DataColumn dc in DgvChangedDT.Columns)
{
  string nameOfColumn = dc.ColumnName; // <----
  OrgVal = dr[dc, DataRowVersion.Original].ToString();
  CurrVal = dr[dc, DataRowVersion.Current].ToString();
  MessageBox.Show("Original Value: " + OrgVal + " ," + " Current Value: " +           CurrVal);
}
// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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