views:

107

answers:

2

I've populated a DataTable with a DataAdapter but I would like to change the values dynamically for all of the rows in that column in the DataTable. How do I go about doing this?

Here is my current code:

SqlConnection conn = null;
string sSQL = "";
string connString = "Datasourceetc";

sSQL = "SELECT TEST_ID FROM TEST_TABLE";

SqlDataAdapter sda = new SqlDataAdapter(sSQL, conn);

DataTable dt = new DataTable();

sda.Fill(dt);

foreach (DataRow row in dt.Rows)
{
  dt.Columns["TEST_ID"] = "changed"; //Not changing it?!
}

GridView1.DataSource = dt;

GridView1.DataBind();

Thanks

A: 

You need to fill first, then change!

SqlConnection conn = new SqlConnection(connString);
string sSQL = "SELECT TEST_ID FROM TEST_TABLE";

DataTable dt = new DataTable();

SqlDataAdapter sda = new SqlDataAdapter(sSQL, conn);

// fill the DataTable - now you should have rows and columns!
sda.Fill(dt);

// one you've filled your DataTable, you should be able
// to iterate over it and change values
foreach (DataRow row in dt.Rows)
{
    row["TEST_ID"] = "changed"; //Not changing it?!
}

GridView1.DataSource = dt;
GridView1.DataBind();

Marc

marc_s
dt.Columns["TEST_ID"] = "changed";This is giving me a error: "System.Data.DataColumnCollection.this[string]' cannot be assigned to -- it is read only
Roy
ah, sorry, didn't see that - of course, when iterating over the rows, you'll need to use that **row** object to set its field values - see my update
marc_s
+1  A: 

Everything above looks good except when iterating through the rows you can access the columns like so...

foreach (DataRow row in dt.Rows)
{
  row["ColumnName"] = "changed"; //Not changing it?!
}
George