Wrox Programmer Forums
Go Back   Wrox Programmer Forums > ASP.NET and ASP > ASP.NET 2.0 > ASP.NET 2.0 Basics
ASP.NET 2.0 Basics If you are new to ASP or ASP.NET programming with version 2.0, this is the forum to begin asking questions. Please also see the Visual Web Developer 2005 forum.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 2.0 Basics section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
Old March 24th, 2006, 01:34 AM
Registered User
Join Date: Mar 2006
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";

//create second row
DataRow row2 = dt.NewRow();
row2["column1"] = "row2col1";
row2["column2"] = "row2col2";

DataGrid1.DataSource = dt;
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;


DataGrid1.DataSource = dt;

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?
Old March 24th, 2006, 01:51 AM
Friend of Wrox
Join Date: Nov 2003
Posts: 1,348
Thanks: 0
Thanked 5 Times in 5 Posts

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.


Similar Threads
Thread Thread Starter Forum Replies Last Post
Datagrid + datatable edukulla C# 2005 2 September 11th, 2006 04:53 PM
datasource for dropdown in datagrid msrnivas General .NET 1 August 8th, 2005 08:17 PM
DataGrid DataSource is Undefined. ochanarachel Classic ASP Basics 1 February 22nd, 2005 06:10 PM
Datagrid functionality without a datasource cesherman VS.NET 2002/2003 1 July 7th, 2003 11:21 PM

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