49

I have a datatable. I need to fetch a certain column value based on the user input. For example, lets say the datatable has two columns CountryID and CountryName.

I need to find CountryID in the datatable based on the user input country name. I could just open a connection with DB and run the query select countryID from Country where countryName = @userinput. Is there anyway i could do this on the datatable.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
peace
  • 837
  • 2
  • 12
  • 18

7 Answers7

77
string countryName = "USA";
DataTable dt = new DataTable();
int id = (from DataRow dr in dt.Rows
              where (string)dr["CountryName"] == countryName
              select (int)dr["id"]).FirstOrDefault();
demonplus
  • 5,613
  • 12
  • 49
  • 68
Seattle Leonard
  • 6,548
  • 3
  • 27
  • 37
22
foreach (DataRow row in Datatable.Rows) 
{
    if (row["CountryName"].ToString() == userInput) 
    {
        return row["CountryID"];
    }
}

While this may not compile directly you should get the idea, also I'm sure it would be vastly superior to do the query through SQL as a huge datatable will take a long time to run through all the rows.

İlker Elçora
  • 610
  • 5
  • 13
Jimmy
  • 9,686
  • 14
  • 59
  • 78
  • Simple and straight to the point but as you said, this can cost alot in the later future. – peace May 26 '10 at 22:02
  • All in all nothing is going to be more efficient than just using SQL, LINQ to Datatables and Datatables / Dataviews will all have to load all of the records into memory and then query them – Jimmy May 27 '10 at 02:50
  • Another option is simply just using linq to sql – Jimmy May 27 '10 at 02:50
  • this is the fastest and direct way to work with a fair amount of data. Best answer IMHO. – Liquid Core Oct 08 '13 at 11:10
17

I suggest such way based on extension methods:

IEnumerable<Int32> countryIDs =
    dataTable
    .AsEnumerable()
    .Where(row => row.Field<String>("CountryName") == countryName)
    .Select(row => row.Field<Int32>("CountryID"));

System.Data.DataSetExtensions.dll needs to be referenced.

Zar Shardan
  • 5,675
  • 2
  • 39
  • 37
Deilan
  • 4,740
  • 3
  • 39
  • 52
  • 2
    This is exactly what I was looking for, thank you! I almost missed your final comment about the reference--thank you for that as well. – kwill Aug 10 '16 at 20:50
2

Datatables have a .Select method, which returns a rows array according to the criteria you specify. Something like this:

Dim oRows() As DataRow

oRows = dtCountries.Select("CountryName = '" & userinput & "'")

If oRows.Count = 0 Then
   ' No rows found
Else
   ' At least one row found. Could be more than one
End If

Of course, if userinput contains ' character, it would raise an exception (like if you query the database). You should escape the ' characters (I use a function to do that).

ACB
  • 970
  • 6
  • 8
2

As per the title of the post I just needed to get all values from a specific column. Here is the code I used to achieve that.

    public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
    {
        return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
    }
cdiggins
  • 17,602
  • 7
  • 105
  • 102
1

I suppose you could use a DataView object instead, this would then allow you to take advantage of the RowFilter property as explained here:

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

private void MakeDataView() 
{
    DataView view = new DataView();

    view.Table = DataSet1.Tables["Countries"];
    view.RowFilter = "CountryName = 'France'";
    view.RowStateFilter = DataViewRowState.ModifiedCurrent;

    // Simple-bind to a TextBox control
    Text1.DataBindings.Add("Text", view, "CountryID");
}
Dalbir Singh
  • 2,629
  • 3
  • 26
  • 29
0

You can also use The Field extension method receives a type parameter. It has several parameter list overloads.

// Get the first & third field's value by column index.

   int weight = dataTable.Rows[0].Field<int>(0);
   string code = dataTable.Rows[0].Field<string>(2);

// Get the second & Fourth field's value by column name.

string name = dataTable.Rows[0].Field<string>("Name");
DateTime date = dataTable.Rows[0].Field<DateTime>("Date");

https://social.msdn.microsoft.com/forums/en-US/339cf1e3-215c-46c8-8721-f608b16cf3ae/how-to-get-the-column-value-from-the-data-table?forum=aspgettingstarted&prof=required

Abdul Khaliq
  • 2,139
  • 4
  • 27
  • 31