How to retrieve data from a specific column in a C# datatable?
You can use the Columns property of the DataTable to retrieve data from a specific column. Here is an example code:
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Rows.Add(1, "John", 25);
dt.Rows.Add(2, "Mary", 30);
dt.Rows.Add(3, "Tom", 35);
// 获取Name列的数据
foreach (DataRow row in dt.Rows)
{
string name = row["Name"].ToString();
Console.WriteLine(name);
}
In the example above, we created a DataTable with three columns: ID, Name, and Age, and added some rows of data. We then used a foreach loop to iterate through each row of the DataTable, retrieve the data from the Name column by column name, and print it out.