Saulius

Saulius

  • NA
  • 12
  • 0

Help me with NullReferenceException, please?

Nov 3 2009 4:34 PM

Hello, Please help me with this code. I am trying to retrieve data from my table row and I dont have a success for two days.

This is a piece of code, witch I think couse a trouble:
 private void ViewDataForm_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("NewTable");
DataSet ds = new DataSet();
ds.Tables.Add(dt);
DataColumn column;

column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
dt.Columns.Add(column);

dt.Columns.Add("Month", typeof(String));
dt.Columns.Add("Balance", typeof(String));

DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = dt.Columns["id"];
dt.PrimaryKey = PrimaryKeyColumns;


String sqlQuery = "";
int counter = 0;

System.Data.SqlServerCe.SqlCeConnection conn = new System.Data.SqlServerCe.SqlCeConnection(
("Data Source=newDB.sdf;Max Database Size=2047"));

try
{
//Let's assing our sql data reader
SqlCeDataReader myReader = null;

// Let's connect to it
conn.Open();
System.Data.SqlServerCe.SqlCeCommand cmd = conn.CreateCommand();

sqlQuery = "SELECT SUM(income-expense) AS Balance, date_y AS Date FROM Income WHERE date = '" + comboBoxCurrentlyShowingYear.SelectedItem + "' GROUP BY date_y ORDER BY " + comboBoxSortBy.SelectedItem + " " + comboBoxASCDESC.SelectedItem;
cmd.CommandText = sqlQuery;
myReader = cmd.ExecuteReader();

while (myReader.Read())
{
counter++;
dt.Rows.Add(counter, myReader[1].ToString(), myReader[0].ToString());
}
dataGridIncome.DataSource = ds.DefaultViewManager.CreateDataView(dt);

int primaryKey = dataGridIncome.CurrentRowIndex + 1;

DataRow findRow = ds.Tables[0].NewRow();

findRow = dt.Rows.Find(primaryKey);

//!#!#! I get a message after that Message.Show() method. It says: NullReferenceException was unhandled. !#!#!
MessageBox.Show("Current row index: " + findRow[0].ToString() + "\nMonth: " + findRow[1].ToString() + "\nBalance: " + findRow[2].ToString());
}
finally
{
//Close that connection NOW
conn.Close();
ds.Tables.Clear();
}
}
I get an error after proceding Message.Show method.
If someone, please, can help me.


Answers (5)