当我单击 dataGridView 时,它说索引超出范围必须是非负数并且小于集合的大小



这是我的代码

private void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        button2.Text = "Update";
        textBox1.Text = dataGridView1.SelectedRows[0].Cells["dgProCode"].Value.ToString();
        textBox2.Text = dataGridView1.SelectedRows[0].Cells["dgProName"].Value.ToString();
        textBox3.Text = dataGridView1.SelectedRows[0].Cells["dgQuantity"].Value.ToString();
        dateTimePicker1.Text = DateTime.Parse(dataGridView1.SelectedRows[0].Cells["dgDate"].Value.ToString()).ToString("dd/MM/yyyy");
        if (dataGridView1.SelectedRows[0].Cells["dgStatus"].Value.ToString() == "Active")
        {
            comboBox1.SelectedIndex = 0;
        }
        else
        {
            comboBox1.SelectedIndex = 1;
        }
    }

双击时,您不会首先检查是否有任何选定的行。在尝试引用第一个之前,请先检查...

if (dataGridView1.SelectedRows == null || dataGridView1.SelectedRows.Count == 0)
    return;
button2.Text = "Update";
textBox1.Text = dataGridView1.SelectedRows[0].Cells["dgProCode"].Value.ToString();
textBox2.Text = dataGridView1.SelectedRows[0].Cells["dgProName"].Value.ToString();
...

只需将数据网格属性,选择模式更改为"FullRowSelect"。

相关内容

最新更新