Error of IndexOutOfRange -- Can not find table 0 -- here is my code it hits the foreach line and throws the error. What should I update so this executes?
SqlCommand comnd = new SqlCommand(query, con);
con.Open();
DataSet ds = new DataSet();
StreamWriter strmwr = new StreamWriter(Location);
foreach (DataRow in ds.Tables[0].Rows
You're never populating the DataSet
- you're creating a SQL command, but never executing it. You're not querying the database at all.
It's not clear whether you really need a DataSet, to be honest - you could potentially just use a reader returned by [
ExecuteReader][1]. Personally I'd go in that direction, as I'm not a big fan of
DataSet`. (Alternatively, I'd use an ORM to avoid all this low-level work...)
(Note that you should use using
statements for your writer, command etc.)
If you really need a DataSet
, you probably want to look at SqlDataAdapter
:
var adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
// Now your DataSet will have data in it
See more on this question at Stackoverflow