为什么在引用DataGridView CurrentRow时会出现异常?

时间:2011-11-29 07:33:10

标签: winforms exception datagridview nullreferenceexception

我正在尝试在DataGridView中获取“更改的currentcell”事件,但每次我尝试加载表单(这是另一种形式的子项)时,我在{{1}中得到一个例外event:

  

SystemNullReferenceException:对象未设置为对象的实例。

我想这是因为我没有选择任何一行。当然我可以使用datagridview_currentcellcatch来绕过,但我想要一种更优雅的方式并知道我做错了什么。

这是我的代码:

Form2.CS

try

Form2.Designer.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;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以测试try{}甚至catch{}是否不是CurrentCell,而不是CurrentRow 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();
    }

答案 1 :(得分:0)

您的dataGridView单元格没有任何价值,而您正试图保存null字符串。

尝试捕获异常并通知用户他必须在单元格中写入内容

try
{
    textBox1.Text = dataGridView1.Rows[dataGridView1.
    CurrentRow.Index].Cells[2].Value.ToString();
}
catch(NullReferenceException)
{ 
    MessageBox.Show("You cannot process an empty cell");
}

请在以下链接中找到更多信息:

https://msdn.microsoft.com/en-us/library/sxw2ez55.aspx