我必须将网格选中的行值显示到文本框中。我正在使用此代码,但它不起作用。任何帮助将不胜感激。
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();
}