DataTable object reference problem

larrycolvin

New member
Joined
Jun 5, 2003
Messages
2
I am having a problem with a DataTable object reference. I get the error message
"System.NullReferenceException: Object reference not set to an instance of an object."
on line 51. The Function1 works fine, the problem in only in Function2. Can anyone
help the rookie out?

1 namespace Test
2 {
3 public class TestClass : System.Web.UI.Page
4 {
5 public DataSet MyDataSet;
6 public DataTable MyDataTable1;
7 public DataTable MyDataTable2;
8
9
10 public void Function1()
11 {
12 MyDataSet = new DataSet();
13 MyDataTable1 = MyDataSet.Tables.Add("DataTable1");
14
15 MyDataTable1.Columns.Add("Col1", typeof(Decimal));
16 MyDataTable1.Columns.Add("Col2", typeof(String));
17
18 MyDataTable2 = MyDataSet.Tables.Add("DataTable2");
19
20 MyDataTable2.Columns.Add("Col1", typeof(Decimal));
21 MyDataTable2.Columns.Add("Col2", typeof(String));
22
23 string CMDStr = "SQL Statement";
24
25 SQLConn = new SqlConnection("Connection String");
26
27 SqlCommand SQLCmd = new SqlCommand(CMDStr, SQLConn);
28
29 SQLConn.Open();
30
31 SqlDataReader SQLReader = SQLCmd.ExecuteReader();
32
33 DataRow MyRow1;
34
35 while (SQLReader.Read())
36 {
37 MyRow1 = dtAvailableElements.NewRow();
38 MyRow1["Col1"] = SQLReader.GetValue(0);
39 MyRow1["Col2"] = SQLReader.GetString(1);
40 dtAvailableElements.Rows.Add(MyRow1);
41 }
42
43 SQLReader.Close();
44 SQLConn.Close();
45 }
46
47 public void Function2()
48 {
49 DataRow MyRow2;
50
51 MyRow2 = MyDataTable2.NewRow();
52 MyRow2["Col1"] = 45;
53 MyRow2["Col2"] = "Test";
54 MyDataTable2.Rows.Add(MyRow2);
55 }
56 }
57 }
 
As the error message quite clearly :-) suggests, there is an object-variable that has not been instanciated (the object it refers to has not been created.)

It appears to me, that in Function2
MyDataTable2 is void.
 
OK, it was just a guess.
Your code does not show that function2 (why not method2?) is called after function1 has been called.
Is it granted that both calls are performed on the identical instance of a TestClass object?


Perhaps the best way is to step through your code with the debugger. Then you can trace exactly, which objects are instantiated and when, and in which line the error occurs.
 
Back
Top