am a begniner in c#.currently am doing a project "Address Book" in C# visual studio 2005.and here am using Oledb connection....i find one error in the following code while debugging..the code is as follows. the error is is in red marked line.But the same code when i used in Visual studio 2003 it works out.and here it shows this error while debugging.and the error is.
NullReferenceException was unhandled.
object Refrence not set to an instance of an object
CODE
private void LoadCurrentItem(){
if (dataGridView1.CurrentRow!= null && dataGridView1.CurrentRow.Index == -1)// Is there any row selected now?{
button2.Enabled =
false;button3.Enabled =
false; return;}
// The first column of the grid contains the id field. Since the width of the // field is set to zero, the column is not visible in the grid. But we // can still access the value in it. // Retrieve the first column from the selected row. int Id = int.Parse(dataGridView1[this.dataGridView1.CurrentRow.Index, 0].ToString()); Address address = AddressManager.GetAddress(Id); if (address == null){
MessageBox.Show("Couldn't retrieve the object for the selected row.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return;}
textBox2.Text = address.name;
textBox3.Text = address.address;
textBox4.Text = address.phone;
textBox5.Text = address.father;
dateTimePicker1.Value = address.DOB;
textBox6.Text = address.Quali;
textBox7.Text = address.Nationality;
textBox8.Text = address.Design;
textBox9.Text = address.Email;
richTextBox1.Text = address.Remark;
}
Steve StovoldPosted Apr 28, 2008, 4:41 PM
If dataGridView1.CurrentRow is null it will throw an error because it will try and evaluate whether the currentrow.index = -1 as well, and can't because it is null.
Try something along these lines:
if (dataGridView1.CurrentRow != null)
{
if (dataGridView.CurrentRow.Index == -1)
{
...........etc etc
Ryan AlfordPosted Apr 28, 2008, 2:45 PM
or, use the Immediate window(debugging tool) and copy and paste that line of code in the immediate window when the breakpoint is hit. that will also give you the value of the column that you are trying to parse to an int.
using "Int.Parse" will throw an null exception if you try to parse a null value.