我有一个
DataGridView
(tblLoggedJobs),它显示用户记录的作业列表。我需要管理员能够更新这些作业以显示作业的任何更新或注释作业是否已关闭。
我希望程序将所选行中的数据显示到右侧的文本框中,但是我不确定如何获取此数据并根据所选行显示它。
您可以使用 SelectedRows 属性。
示例:
if(dataGridView1.SelectedRows.Count > 0) // make sure user select at least 1 row
{
string jobId = dataGridView1.SelectedRows[0].Cells[0].Value + string.Empty;
string userId = dataGridView1.SelectedRows[0].Cells[2].Value + string.Empty;
txtJobId.Text = jobId;
txtUserId.Text = userId;
}
在cellclick事件中添加代码
if (e.RowIndex >= 0)
{
//gets a collection that contains all the rows
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
//populate the textbox from specific value of the coordinates of column and row.
txtid.Text = row.Cells[0].Value.ToString();
txtfname.Text = row.Cells[1].Value.ToString();
txtlname.Text = row.Cells[2].Value.ToString();
txtcourse.Text = row.Cells[3].Value.ToString();
txtgender.Text = row.Cells[4].Value.ToString();
txtaddress.Text = row.Cells[5].Value.ToString();
}
有关更多信息,请使用此链接如何使用 C# 将 Datagridview 中的选定行显示到文本框中
private void orderpurchasegridview_CellClick(object sender, DataGridViewCellEventArgs e)
{
int ind = e.RowIndex;
DataGridViewRow selectedRows = orderpurchasegridview.Rows[ind];
txtorderid.Text = selectedRows.Cells[0].Value.ToString();
cmbosuppliername.Text = selectedRows.Cells[1].Value.ToString();
cmboproductname.Text = selectedRows.Cells[2].Value.ToString();
txtdate.Text = selectedRows.Cells[3].Value.ToString();
txtorderquantity.Text = selectedRows.Cells[4].Value.ToString();
}
private void MyDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dg = (DataGrid)sender;
DataRowView rs = dg.SelectedItem as DataRowView;
if(rs != null)
{
textBoxJobId.Text = rs["JobId"].ToString();
}
}
始终使用 CellEnter 事件,因为它可以与键盘箭头键和鼠标单击一起使用。 始终使用 dataGridView1.SelectedCells.Count > 0 "SelectedCells 否则您必须选择完整行。
private void dataGridView1_CellEnter(对象发送者,DataGridViewCellEventArgs e) { if (dataGridView1.SelectedCells.Count > 0) // 确保用户至少选择 1 个单元格 {
DataGridToTextboxes(e.RowIndex);
}
}
private void DataGridToTextboxes(int x)
{
//try a seperate method to show gridview to text boxes, you can you same method for multiple events.
string Item1 = dataGridView1.Rows[x].Cells[1].Value + string.Empty;
string MinRange = dataGridView1.Rows[x].Cells[2].Value + string.Empty;
string MaxRange = dataGridView1.Rows[x].Cells[3].Value + string.Empty;
string MinStable = dataGridView1.Rows[x].Cells[4].Value + string.Empty;
string MaxStable = dataGridView1.Rows[x].Cells[5].Value + string.Empty;
txtItem.Text = Item1;
TextMinRange.Text = MinRange;
TextMaxRange.Text = MaxRange;
TextMinStable.Text = MinStable;
TextMaxStable.Text = MaxStable;
}