如何在C#Windows应用程序中获取网格的列值?
当我点击单元格时,它应该得到列值。
private void gridAgentDetails_Click(object sender, EventArgs e) { for (int i = 0; i < this.gridAgentDetails.CurrentRowIndex; i++) { string str = gridAgentDetails.Text; } }
使用DataGridView.CurrentCell.Value
:
String result = this.gridviewAgentDetails.CurrentCell.Value.ToString();
DataGridView.CurrentCell属性获取当前活动的单元格。
DataGridViewCell.Value属性获取与此单元格关联的值。
要获取所选单元格的值,请按照以下代码进行操作
int CNo = datagrid.CurrentCellAddress.Y; int StNum = (int)datagrid.Rows[CNo].Cells[0].Value; string StName = (string)datagrid.Rows[CNo].Cells[1].Value; int MrksSecured = (int)datagrid.Rows[CNo].Cells[2].Value;
试试这个eventHandler:[我试过了,我得到了结果]
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { int rowIndex = e.RowIndex; int colIndex = e.ColumnIndex; MessageBox.Show(dataGridView1[colIndex, rowIndex].Value.ToString()); }
既然你评论说你正在使用DataGrid ,这是一个WPF应用程序,而不是一个表单应用程序。
WPF DataGrid控件是数据的直观表示形式,不能直接从DataGrid中读取特定的单元格,因此,除非将其绑定到数据源,否则无法在DataGrid上选择特定的行或列。
DataGrid被设计为与DataTable一起使用。 看到这个链接看看DataGrid是如何绑定到DataTable的 。
然后,要读取DataGrid中的特定单元格值,可以改为读取DataTable(例如dataTable1[RowNumber][ColumnName]
,其中RowNumber是一个int,ColumnName是一个字符串。