View Single Post
  #1 (permalink)  
Old March 24th, 2006, 01:34 AM
Jamal Junior Jamal Junior is offline
Registered User
 
Join Date: Mar 2006
Location: , , .
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default 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!
Reply With Quote