C# getting values from DataTable or BindingSource

允我心安 提交于 2019-12-25 05:14:39

问题


I have a labels that need values retreieved from a Database.

I am able to query the database but how can I extract values from a DataTable and place them in the appropiate labels

Thanks


回答1:


In DataTable you have rows and columns. To select a particular cell you need to do this:

label1.Text = dataTable[0][0];

This will set the label1 text to Row 0, Column 0 value.

To iterate through each row use:

foreach(DataRow row in dataTable.Rows)
{
Console.WriteLine(row["ColumnName1"]);
Console.WriteLine(row["ColumnName2"]);
Console.WriteLine(row["ColumnName3"]);
Console.WriteLine(row["ColumnName4"]);
}

This will print values for columns against each row. In this code you need to replace string for columnname (e.g. ColumnName1) with your column names




回答2:


Example of how you retrieve a value from the first row and the column named "MyFirstColumn":

label1.Text = myDataTable.Rows[0]["MyFirstColumn"]


来源:https://stackoverflow.com/questions/10147588/c-sharp-getting-values-from-datatable-or-bindingsource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!