如何在 SelectionChanged 事件 C# 的文本框中显示网格行值?

How to show grid row value in textBox on SelectionChanged event C#?

我必须使用此代码将网格选定的行值显示到 textboxes.I' 中,但它不起作用。任何帮助将不胜感激。

 private void CRUD_SelectionChanged(object sender, EventArgs e)
    {

        txtBoxID.Text = CRUD.SelectedRows[0].Cells[0].Value.ToString();
        txtBoxStates.Text = CRUD.SelectedRows[1].Cells[1].Value.ToString();
        txtBoxName.Text = CRUD.SelectedRows[2].Cells[2].Value.ToString();
        txtBoxAddress.Text = CRUD.SelectedRows[3].Cells[3].Value.ToString();
        txtBoxCenter.Text = CRUD.SelectedRows[4].Cells[4].Value.ToString();
        txtBoxCity.Text = CRUD.SelectedRows[5].Cells[5].Value.ToString();
    }

您正在为所选行编制索引。如果您选择的行少于 6 行,那么您将超出范围。您可能只想从一行中获取数据。检查是否只选择了一行,然后使用索引 0。确保设置 CRUD.MultiSelect = false

或者使用 CRUD.CurrentRow,这只会让你排成一行。

Form.Designer.cs:

this.CRUD.SelectionChanged += new System.EventHandler(this.CRUD_SelectionChanged);

Form.cs:

private void CRUD_SelectionChanged(object sender, EventArgs e)
{
    txtBoxID.Text = CRUD.CurrentRow.Cells[0].Value.ToString();
    txtBoxStates.Text = CRUD.CurrentRow.Cells[1].Value.ToString();
    txtBoxName.Text = CRUD.CurrentRow.Cells[2].Value.ToString();
    txtBoxAddress.Text = CRUD.CurrentRow.Cells[3].Value.ToString();
    txtBoxCenter.Text = CRUD.CurrentRow.Cells[4].Value.ToString();
    txtBoxCity.Text = CRUD.CurrentRow.Cells[5].Value.ToString();
}