Search code examples
winformsexceptiondatagridviewnullreferenceexception

Why do I get an exception when I reference DataGridView CurrentRow?


I'm trying to get a "changed currentcell" event in DataGridView, but every time I try to load the form (which is a child of another form), I get an exception in the datagridview_currentcell event:

SystemNullReferenceException: object not set to an instance of an object.

I guess it's because I haven't selected any row. Of course I can use catch and try to bypass, but I want a more elegant way and to know what am I doing wrong.

Here's my code:

Form2.CS:

namespace AsefotSystem
{
    public partial class ownerReport : Form
    {
        public ownerReport()
        {
            InitializeComponent();
            loadDB();
            setGrid();
        }

        private void loadDB()
        {
            string connetionString = null;
            OleDbConnection connection;
            OleDbDataAdapter oledbAdapter;

            DataSet ds = new DataSet();
            string sql2 = null;
            connetionString = ConfigurationManager.ConnectionStrings["RiskDB"].ConnectionString;              
            sql2 = "select * From tbl2_asefot";
            connection = new OleDbConnection(connetionString);

            try
            {
                connection.Open();

                oledbAdapter = new OleDbDataAdapter(sql2, connection);
                oledbAdapter.Fill(ds, "Asefot");
                oledbAdapter.Dispose();

                connection.Close();
                dsAsefotGrid = ds;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void setGrid()
        {
            Controls.Add(dataGridView1);
            dataGridView1.DataSource = dsAsefotGrid.Tables[0];
        }

        private void dataGridView1_CurrentCell(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString();
                textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        DataSet dsAsefotGrid;
    }
}

Form2.Designer.CS:

this.dataGridView1.CurrentCellChanged += new System.EventHandler(this.dataGridView1_CurrentCell);

Solution

  • Instead of the try{} catch{}, you could test if the CurrentCell or even CurrentRow is not null.

        if(dataGridView1.CurrentCell != null)
        {
            textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString();
            textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
        }