user1080533
user1080533

Reputation: 865

C# DataTable edit cell in specific row with Linq

i have a DataTable table and few TextBox controls. When I click button I need to change the "Value" collumn, where ID matches the text input.

DataTable table = new DataTable();
table.Columns.Add("ID", typeof(string));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Value", typeof(decimal));
table.Columns.Add("Unit", typeof(string));

string myId=txtId.Text;
decimal myValue=txtValue.Text;

I know how to check if ID exists in the table. How do I change the value of the field "Value"?

bool contains = table.AsEnumerable().Any(row => myID == row.Field<string>("ID"));
if (contains == true)
{
     //Change the value of row.Field<string>("Value")!!
}

Thank you for help.

EDIT: Here is my solution:

string s = "ID='" + myId + "'";
DataRow dr = table.Select(s).FirstOrDefault();
dr["Value"] = myValue;

Upvotes: 0

Views: 1976

Answers (1)

Sid M
Sid M

Reputation: 4354

Try this:

DataRow dr = table.Select("ID=myId").FirstOrDefault(); 
dr["Value"] = "your value";

Upvotes: 1

Related Questions