How to Get a Specific Column Value from a DataTable?

前端 未结 6 1905
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 02:08

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

相关标签:
6条回答
  • 2020-12-13 02:19

    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).

    0 讨论(0)
  • 2020-12-13 02:23

    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)));
        }
    
    0 讨论(0)
  • 2020-12-13 02:32
    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.

    0 讨论(0)
  • 2020-12-13 02:35
    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();
    
    0 讨论(0)
  • 2020-12-13 02:42

    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");
    }
    
    0 讨论(0)
  • 2020-12-13 02:44

    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.

    0 讨论(0)
提交回复
热议问题