EverTheLearner
EverTheLearner

Reputation: 7200

How do you change specific data in a datatable column?

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

Upvotes: 2

Views: 10246

Answers (2)

marc_s
marc_s

Reputation: 754268

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

Upvotes: 0

George
George

Reputation: 7944

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?!
}

Upvotes: 3

Related Questions