DataTable from DataGrid.DataSource
I have a form with
1 DataGrid
2 TextBoxes and
1 Button
the following Page_Load:
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("column1", typeof(String)));
dt.Columns.Add(new DataColumn("column2", typeof(String)));
//Create first row
DataRow row1 = dt.NewRow();
row1["column1"] = "row1col1";
row1["column2"] = "row1col2";
dt.Rows.Add(row1);
//create second row
DataRow row2 = dt.NewRow();
row2["column1"] = "row2col1";
row2["column2"] = "row2col2";
dt.Rows.Add(row2);
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
--------------------------------------------------
and the following Button1_Click:
DataTable dt = (DataTable)DataGrid1.DataSource;
//create a row
DataRow row = dt.NewRow(); //****** ERROR ******
row["column1"] = TextBox1.Text;
row["column2"] = TextBox2.Text;
dt.Rows.Add(row);
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
TextBox1.Text = "";
TextBox2.Text = "";
--------------------------------------------
Basically I want to include a new row into the table-like structure with the text I just typed. eventually I want to save it into the database.
When I click the button an error message comes up saying that
"Object reference not set to an instance of an object."
Because my variable "dt" is not instanced.
How could I get around this problem?
Is there an easier way of doing that?
Thanks!
|