Reputation: 173
Am I over-writing the datatable when I think I am adding columns to it? I know that if I write to the output window in my _FinishButton() event my results are there, but when I write to output in my pushdatatosql() method it is empty. I have the Datatable desclared as a class variable.
What am I incorrectly coding here?
DataTable dtResult = new DataTable();
protected void FinishBtn_Click(object sender, EventArgs e)
{
pushdatatosql();
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
DataRow dr = null;
dtResult.Columns.Add(new DataColumn("mainevent", typeof(string)));
dtResult.Columns.Add(new DataColumn("secondevent", typeof(string)));
foreach (GridViewRow gr in grdOther.Rows)
{
dr = dtResult.NewRow();
TextBox box1 = (TextBox)gr.Cells[1].FindControl("txtmainevent");
TextBox box2 = (TextBox)gr.Cells[2].FindControl("txtse");
dr["mainevent"] = box1.Text;
dr["secondevent"] = box2.Text;
dtResult.Rows.Add(dr);
}
}
protected void pushdatatosql()
{
foreach (DataRow dataRow in dtResult.Rows)
{
foreach (var item in dataRow.ItemArray)
{
System.Diagnostics.Debug.WriteLine(item);
}
}
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLString"].ConnectionString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
foreach (DataColumn c in dtResult.Columns)
bulkCopy.ColumnMappings.Add(c.ColumnName, c.ColumnName);
bulkCopy.DestinationTableName = "TestInsertTable";
bulkCopy.WriteToServer(dtResult);
}
}
}
Upvotes: 1
Views: 786
Reputation: 2855
The dtResult
class variable you refer to only lasts for as long as the request. So for each post-back you make in your page, a new instance of this class and that class member will be created. In Webforms the "Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded." MSDN. At this point your class variable is destroyed, along with any values it holds.
To resolve this you can try to store your values instead in the view state. Which persists across requests.
Upvotes: 1