Greetings. I have a DataGridView filled with a table from the database on my form. You need to get all the Name in a separate List<> but not from the DataGridView but directly from the DataTable object. Is it possible?

enter image description here

Method that returns a DataTable:

 public DataTable materialsNEW() { DataTable table = new DataTable(); try { using (SqlConnection conn = new SqlConnection(connectionString)) { string get = "select * from Materials"; SqlCommand comd = new SqlCommand(get, conn); DataTable mattable = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(comd); adapter.Fill(mattable); conn.Open(); table = mattable; } } catch (Exception ex) { MessageBox.Show(ex.Message, ex.Source); } return table; } 
  • Well, show datagridview fill datagridview and you can immediately give you an answer, so, for now, you can only guess. You can get the list, but your code is needed - Denis Bubnov
  • Does it affect? Code added - Sergey
  • one
    does not affect. var names = table.AsEnumerable().Select(row => row.Field<string>("Name")).ToList(); - Ev_Hyper
  • 2
    or var names = table.AsEnumerable().Select(row => row["Name"]).ToList(); - Ev_Hyper
  • 2
    yes, this is linq , you can read about the second question here: What is a lambda expression or on msdn - Ev_Hyper

2 answers 2

Somehow it should be:

 List<string> names = new List<string>(); foreach(DataRow row in table.Rows) names.Add(row["Name"].ToString()); 

After filling in your DataTable table - write this code and get what you need.

  • one
    Ah, well done - 20 seconds earlier. - Igor
 ... List<string> names = new List<string>(); foreach(DataRow row in mattable.Rows) names.Add(System.Convert.ToString(row["Name"]));