Two forms and separate class(DataConn) for data access in my project. Button from Form1 opens Form2 and this(child) form calls GetData method from DataConn class to populate Form2 textbox with a name. Form2 has button for retrieving next record which is calling the NavigateRecords method in DataConn class. The NavigateRecord method is called from inside GetData in order to populate the textbox in Form2, when it loads, but also for retrieving next record from Form2’s Next event. When NavigateRecords is called from Form2 Next button event the error ‘Object reference not set to an instance of an object’ on this line: myDR = myDS.Tables["People"].Rows[increment]; in NavigateRecords. Why does this not happen when the same line executes upon Form2 load event? If I create an instance of the DataRow the warning 'System.Data.DataRow(System.Data.DataRowBuilder) is inaccessible due to its protection level.
DataConn class:
public class DataConn
{
private DataSet myDS;
private DataRow myDR;
private int maxRows = 0;
private int increment = 0;
private string name;
public int MaxRows
{ get { return maxRows; } }
public int Increment
{ get { return increment; } set { increment = value; } }
public string Name
{ get { return name; } }
public void GetData()
{
// class variable
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Testing\TestDatabase.accdb";
//everything created in 'using' gets destroyed/goes out of scope at end of 'using' block.
using (OleDbConnection myConn = new OleDbConnection(connectionString))
{
string SQL = "SELECT * From Test";
OleDbDataAdapter myDA = new OleDbDataAdapter(SQL, myConn);
myDS = new DataSet();
try
{
myConn.Open();
myDA.Fill(myDS, "People");
NavigateRecords(); //called to populate textbox in NewForm
maxRows = myDS.Tables["People"].Rows.Count;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
myConn.Close();
}
}
}
public void NavigateRecords()
{
try
{
myDR = myDS.Tables["People"].Rows[increment];//exception
name = myDR.ItemArray.GetValue(1).ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
}
Form2 Load and Next_CLick events:
private void frmNewForm_Load(object sender, EventArgs e)
{
DataConn theConn = new DataConn();
theConn.GetData();
txtName.Text = theConn.Name;
}
private void btnNext_Click(object sender, EventArgs e)
{
DataConn theConn = new DataConn();
if (theConn.Increment != theConn.MaxRows - 1)
{
theConn.Increment++;
theConn.NavigateRecords();
FillTextBox();
}
EDIT: I created a new project and included everything within the form class itself. Datarow is initially null and when called in NavigateRecords method is set to System.Data.DataRow and remains so as long as form is open. In my original project when the the datarow is called again from Form2’s next event it is back to null and exception is thrown. Why does it matter that it is null when it was null to start with?