Reading DataSet in C#
If we have filled a DataSet using a select query in C#, how can we read the column values?
I want to do something like this:
string name = DataSetObj.rows[0开发者_如何学Python].columns["name"]
What would the correct syntax look like to achieve my goal?
foreach(var row in DataSetObj.Tables[0].Rows)
{
Console.WriteLine(row["column_name"]);
}
If you already have a dataset, it's something like this;
object value = dataSet.Tables["MyTable"].Rows[index]["MyColumn"]
If you are using a DataReader:
using (SqlCommand cmd = new SqlCommand(commandText, connection, null))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
testID = (int)reader["id"];
}
}
}
sligthly different from what you posted
object value = DataSetObj.Tables["Table_Name"].Rows[rowIndex]["column_name"]
Also, instead of Table_Name and Column_Name you can use the index
You could put it into a common method.
C#
public static string GetRowValue(DataRow row, string name) {
if (!IsDBNull(row[name])) {
return row[name].ToString();
}
return string.Empty;
}
VB
Public Shared Function GetRowValue(ByVal row As DataRow, ByVal name As String) As String
If Not IsDBNull(row(name)) Then
Return row(name).ToString()
End If
Return String.Empty
End Function
var result = from a in ds.Tables[0].AsEnumerable() select new[] {a[0].ToString()};
AsEnumerable()
loads every record into application memory, and then we push the records into the string array.
精彩评论