如何从foreach循环内的字典中调用数据集?在下面的代码中.Rows不存在,并且foreach循环中的数据集为null。
public class dictWITHdataset
{
public dictWITHdataset()
{
DataSets = new Dictionary<string, DataSet>();
}
public IDictionary<string, DataSet> DataSets { get; private set; }
public DataSet readrows(DataSet dataset)
{
string query = "SELECT * FROM test.dbo.test";
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
adapter.Fill(dataset);
return dataset;
}
}
我后来尝试从foreachloop中的字典调用数据集,但它声称Rows确实存在并且它为null。
dictWITHdataset dict = new dictWITHdataset();
DataSet data = new DataSet();
dict.DataSets("Dictionary1",data) //not sure if correct way to call data set
foreach (System.Data.DataRow row in dict.DataSets["Dictionary1"].Rows)
{
@:row["id"] + " " + row["name"];
}
答案 0 :(得分:2)
您忘记调用dict.readrows调用,因此它只添加一个空数据集。另外,readrows不需要参数,你可以在函数中创建它。
dictWITHdataset dict = new dictWITHdataset();
DataSet data = new DataSet();
dict.DataSets("Dictionary1",dict.readrows(data))
foreach (System.Data.DataRow row in dict.DataSets["Dictionary1"].Rows)
{
@:row["id"] + " " + row["name"];
}