How do I call a data set from a dictionary inside of a foreach loop? In the code below .Rows doesn’t exist and the dataset is null in the foreach loop.
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;
}
}
I later try to call the dataset from a dictionary in a foreachloop but it claims Rows does exist and its 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"];
}
You have forgot to call dict.readrows call, thus it only adds an empty dataset. Also, readrows does not need to take a parameter, you can create it in the function.