Reading DataSet in C#

别来无恙 提交于 2020-06-22 10:36:09

问题


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].columns["name"]

What would the correct syntax look like to achieve my goal?


回答1:


foreach(var row in DataSetObj.Tables[0].Rows)
{
    Console.WriteLine(row["column_name"]);
}



回答2:


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"];
        }
    }
}



回答3:


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




回答4:


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



回答5:


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.



来源:https://stackoverflow.com/questions/6692706/reading-dataset-in-c-sharp

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