我在datagridview上添加了右键菜单,为了单击右键时选中整行
我也在datagridview的contextMenuStrip上把这个右键菜单添加上了,
但是,程序在运行的时候需要左键单击一下datagridview再右键才能选中整行,
直接右键会提示“未将对象引用到对象的实例”
这是什么原因呢?
try
            {
                if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1)
                {
                    dataGridView1.CurrentCell.Selected = false;
                    dataGridView1.Rows[e.RowIndex].Selected = true;
                    dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

解决方案 »

  1.   

    dataGridView1.CurrentCell.Selected = false;将这句换成
    dataGridView1.CurrentRow.Selected = false;
    也还是不行    CurrentRow为空  怎么办
      

  2.   


                try
                {
                    if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1)
                    {
                        if (dataGridView1.CurrentCell != null)
                            dataGridView1.CurrentCell.Selected = false;
                        dataGridView1.Rows[e.RowIndex].Selected = true;
                        dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }