Updating DataTable cell?

  • Thread starter Thread starter Brett Romero
  • Start date Start date
B

Brett Romero

Is there a way to update data in a DataTable cell? I have column dates
that are string type. I want to add another column to this table:

dt.Columns.Add(new DataColumn("Datecolumn2", typeof(DateTime)));

Then loop through the table adding all of the string dates to the same
row but in the new DateTime typed column, which allows me to sort by
date when I feed a Datagrid this table.

How do I update a single cell in a DataTable?

Thanks,
Bretta
 
for (int i=0;i<dt.Rows.Count;i++) {

dt.Rows["DateColumn2"] =
Convert.ToDateTime(dt.Rows["DateColumn1"]);

}

Obviously this code has no validation check that the string in dc1 is
in fact a valid datetime.
 
Right. I'll do that before inserting.

Do you agree with the way I'm going about sorting this? Just wondering
if there is a better way.

Thanks,
Brett
 
The logic is sound to me, but it also depends how big your table is
likely to get I suppose.
It also depends if the value in the date column will be changeable by
the user.

Could you not perhaps implement your own sort method that just sorts by
the string value?
That could be an alternative. It would save you having to mess around
with all those extra values.
You would not need to call that previous code snippet every time the
data gets updated.

You can create your own sort routine by implementing the IComparer
interface.
Then with some string management you can analyse the string format by
converting it to a date and then comparing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top