当我选择第一行时,我得到的行索引为1,如果我没记错的话,必须为0,而在选择第二行和第三行时必须为2。
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (this.dataGridView1.SelectedRows.Count > 0)
{
r = this.dataGridView1.SelectedRows[0].Index;
}
}
private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
p = p+1;
if (p == 1)
{
if (this.dataGridView1.SelectedRows.Count > 0)
{
brand = dataGridView1.Rows[r].Cells[0].Value.ToString();
datadisp();
}
}
}
}
答案 0 :(得分:0)
如果要在Enter键上执行主要操作,则无需在r
事件的dataGridView1_SelectionChanged
中存储选定的行索引。您可以在按键事件中访问选定的行。因此,请删除dataGridView1_SelectionChanged
并更新dataGridView1_KeyPress
的代码,如下所示。
private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
p = p+1;
if (p == 1)
{
if (this.dataGridView1.SelectedRows.Count > 0)
{
brand = this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
datadisp();
}
}
}
}