Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

DataTable Reference problem in c#

larrycolvinlarrycolvin Posts: 3Member
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("Col1", 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["ElementCode"] = 45;
53 MyRow2["ElementName"] = txtFieldName.Text;
54 MyDataTable2.Rows.Add(MyRow2);
55 }
56 }
57 }


Sign In or Register to comment.