Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a DataTable in C# without using a loop?

Tags:

c#

.net

datatable

Let suppose there are three columns in my DataTable

  1. code

  2. name

  3. color

If I know the code and name, how can I update the color of that specific row whose code and name match my criteria? I want to do this without using Loops!

like image 565
Zain Ali Avatar asked May 21 '11 10:05

Zain Ali


People also ask

How to Update DataSet row value in c#?

To edit an existing row in a DataTable, you need to locate the DataRow you want to edit, and then assign the updated values to the desired columns. If you don't know the index of the row you want to edit, use the FindBy method to search by the primary key: C#


1 Answers

You can use LINQ:

DataRow dr = datatable.AsEnumerable().Where(r => ((string)r["code"]).Equals(someCode) && ((string)r["name"]).Equals(someName)).First();
dr["color"] = someColor;

Of course I'm assuming all those criteria are strings. You should change the casts to the correct types.

like image 82
Farinha Avatar answered Oct 08 '22 22:10

Farinha