p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   ASP.NET 2.0 Basics (http://p2p.wrox.com/forumdisplay.php?f=136)
-   -   DataTable from DataGrid.DataSource (http://p2p.wrox.com/showthread.php?t=40303)

Jamal Junior March 24th, 2006 01:34 AM

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!

jbenson001 March 24th, 2006 01:51 AM

Are you using asp.net 2.0? If so use the grid view. If not, the problem is that on the button click the datasource for the datagrid is not defined. You would need to persist the datasource dt in a session variable and then reference it.

Jim



All times are GMT -4. The time now is 03:05 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.