Reputation: 203
I'm relatively new to using DataSets and DataTables in Visual Studio, and am currently trying to populate a DataTable to query for a SQL Insert statement. What I'm using right now is this.
string query = "USE [Database] SELECT e.ID, e.FieldTypeDesc, e.FieldTypeNum, e.tblFieldRefID, f.TableName, f.RefColumn, f.ColumnName FROM tblEnum e JOIN tblFieldRef f ON e.tblFieldRefID = f.ID;";
string field0; //field0 - field12 declared
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
MRWPDataSet1 dsMRWP = new MRWPDataSet1();
SqlCommand cmdMRWP = new SqlCommand(query, conn);
SqlDataAdapter daMRWP = new SqlDataAdapter();
daMRWP.SelectCommand = cmdMRWP;
daMRWP.Fill(dsMRWP);
Which all seems to work as planned. When I get to this part, though...
foreach (DataRow drMRWP in dsMRWP.Tables[0].Rows)
{
field0 = drMRWP["Field0"].ToString();
field1 = drMRWP["Field1"].ToString(); //for field0 - field12
string update = "INSERT INTO [dbo].[Table] ([Code], [Description], [SendEmail], [Type], [CustomForeColor], [Inactive], [ModifiedDate], [CreatedDate], [ModifiedById], [CreatedById], [StartDate], [EndDate]) VALUES (field1, field2, field3, field4, field5, field5, field6, field7, field8, field9, field10, field11, field12)";
SqlCommand upd = new SqlCommand(update, conn);
}
it is skipped entirely, with apparently no values stored in drMRWP. It isn't even stepped into in debugging, just stepped over.
I'm new to all of this, so chances are I overlooked something or made a mistake somewhere, but damned if I can see what it might be. Any insight offered toward that, or suggestions to simplify what might otherwise be overly-complicated, sloppy code would be greatly appreciated.
Upvotes: 0
Views: 293
Reputation: 460018
Since you are using a strongly typed DataSet
i assume that it contains multiple tables. So either use a "normal" DataSet
and keep using Tables[0]
or use the correct table which is an autogenerated type deriving from DataTable
.
For example (presuming the auto generated type of the table is tblEnum
):
foreach (DataRow drMRWP in dsMRWP.tblEnum)
{
// ...
}
It also has strongly typed DataRows
which additional properties you'll lose if you cast it to DataRow
in the foreach
. So replace DataRow
with tblEnumRow
(the name is derived from the table-name).
Upvotes: 1