如何在 C# Windows 应用程序中获取网格的列值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6466815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 17:10:27  来源:igfitidea点击:

How to get column value of grid in C# Windows application?

c#windowsdatagrid

提问by rams

How to get column value of grid in C# Windows application?

如何在 C# Windows 应用程序中获取网格的列值?

When I clicked on the cell, at that time it should get column values.

当我单击单元格时,它应该会获得列值。

private void gridAgentDetails_Click(object sender, EventArgs e)
{
    for (int i = 0; i < this.gridAgentDetails.CurrentRowIndex; i++)
    {
        string str = gridAgentDetails.Text;
    }

}

回答by Akram Shahda

Use DataGridView.CurrentCell.Value:

使用DataGridView.CurrentCell.Value

String result = this.gridviewAgentDetails.CurrentCell.Value.ToString();


DataGridView.CurrentCell Propertygets the currently active cell.

DataGridView.CurrentCell 属性获取当前活动的单元格。

DataGridViewCell.Value Propertygets the value associated with this cell.

DataGridViewCell.Value 属性获取与此单元格关联的值。

回答by Sai Kalyan Kumar Akshinthala

To get the Values of the Selected Cells Follow the Below Code

要获取所选单元格的值,请遵循以下代码

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;

回答by deepi

try this eventHandler: [I tried with this and i got result]

试试这个 eventHandler:[我试过这个,我得到了结果]

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        int rowIndex = e.RowIndex;
        int colIndex = e.ColumnIndex;
        MessageBox.Show(dataGridView1[colIndex, rowIndex].Value.ToString());
    }

回答by KMC

Since you comment saying you're using DataGrid, this is a WPF application, not a Form application.

由于您评论说您正在使用DataGrid,因此这是一个 WPF 应用程序,而不是一个 Form 应用程序。

WPF DataGrid Control is visual representation of data, you cannot read a specific cell directly out of a DataGrid, Hence you cannot select a specific row or column on a DataGrid, unless you bind it to a data source.

WPF DataGrid 控件是数据的可视化表示,您无法直接从DataGrid读取特定单元格,因此您无法选择DataGrid上的特定行或列,除非将其绑定到数据源。

DataGridis designed to use with DataTable. See this linkto see how DataGridis binded to DataTable.

DataGrid旨在与DataTable一起使用。请参阅此链接以了解DataGrid如何绑定到DataTable

Then, to read a specific cell value in DataGrid, you would read the DataTable instead (e.g. dataTable1[RowNumber][ColumnName]where RowNumber is an int, and ColumnName is a string.

然后,要读取 DataGrid 中的特定单元格值,您将改为读取 DataTable(例如dataTable1[RowNumber][ColumnName],其中 RowNumber 是一个 int,而 ColumnName 是一个字符串。