Click here to Skip to main content
15,887,344 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I have a DataTable and want to access the value in cell row 1 and then replace this value. On click nothing is happening, no error or anything.
C#
private void btnTest_Click(object sender, EventArgs e)
{
    DataTable table = new DataTable();
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Rows)
        {
            object value = row[col.ColumnName];
            if (row["TestCase1"].Equals ("Fruit"))
            {
                row["TestCase1"] = "CDE";
            }
        }
    }
}


What I have tried:

I have tried to check my if statements against the excel sheet.
Posted
Updated 1-Dec-22 23:12pm
v2

1 solution

Of course nothing is happening, as your code does not work on any data. You have the following:
C#
private void btnTest_Click(object sender, EventArgs e)
{
    DataTable table = new DataTable(); // you create a new empty DataTable
    foreach (DataRow row in table.Rows)
    {
// ...

As you can see table does not contain any rows or columns, so there is nothing to work on. You must first read some data into it. Or, assuming you initialise a DataTable somewhere else, you need to access the table that contains the actual records.
 
Share this answer
 
Comments
Fernando Matshabe 2-Dec-22 5:15am    
With this very code I am getting an error "unable to cast object of type 'System.Data.DataRow' to type 'System.Data.DataColumn" can you please help me with that.
Richard MacCutchan 2-Dec-22 5:26am    
foreach (DataColumn col in table.Rows)

the Rows collection is a collection of DataRow objects, not DataColumn. The code should be:
foreach (DataColumn col in row) // iterate the columns in this row
Fernando Matshabe 5-Dec-22 7:19am    
this solution did not work
Richard MacCutchan 5-Dec-22 9:14am    
What solution are you referring to? If you have tried some different code and still have a problem then you need to show us the details. So use the Improve question link below your question, and update the question with complete details of what you have changed and what results you get.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900