WPF Datagrid 读取单元格值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3368302/
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
WPF Datagrid read a cell value
提问by dontpanic
I am trying to find out how to read the value of my WPF datagrid cells.
我试图找出如何读取我的 WPF 数据网格单元格的值。
something along the lines of
类似的东西
String myString = myDataGrid.Cells[1][2].ToString();
the datagrid has been created in XAML and i have populated the datagrid with row data by using
数据网格是在 XAML 中创建的,我已经使用行数据填充了数据网格
reportGrid.Items.Add(new cbResultRow() { ... });
now I want to go back and read cell values in my datagrid.
现在我想返回并读取数据网格中的单元格值。
I have seen some examples of reading data from a selected row or cell, by I don't have any selection (the user doesnt interact with the datagrid).
我已经看到了一些从选定行或单元格读取数据的示例,因为我没有任何选择(用户不与数据网格交互)。
i have also seen code like
我也看过类似的代码
foreach(DataGridRow myrow in myDataGrid.Rows)
however the compiler says Rows is not a member of datagrid.
但是编译器说 Rows 不是 datagrid 的成员。
I have searched for several hours to try to find out how to do what I would have thought was a very simple thing!
我已经搜索了几个小时试图找出如何做我认为是一件非常简单的事情!
please help,
请帮忙,
Thanks, will.
谢谢,会。
回答by jsmith
The WPF datagrid was built to bind to something like a DataTable. The majority of the time, you will modify the DataTable, and the Rows/Columns within the DataTable that is bound to the DataGrid.
WPF 数据网格被构建为绑定到数据表之类的东西。大多数情况下,您将修改 DataTable 以及绑定到 DataGrid 的 DataTable 中的行/列。
The DataGrid itself is the Visual Element for the DataTable. Here is a pretty good tutorial on how to do this. To modify data within a loop would look something like this.
DataGrid 本身是 DataTable 的可视元素。这是一个关于如何执行此操作的非常好的教程。在循环中修改数据看起来像这样。
foreach(DataRow row in myTable.Rows)
{
row["ColumnTitle"] = 1;
}
This would simply make all the values in Column "ColumnTitle" equal to 1. To access a single cell it would look something like this.
这只会使“ColumnTitle”列中的所有值都等于 1。要访问单个单元格,它看起来像这样。
myTable.Rows[0][0] = 1;
This would set the first cell in your DataTable to 1.
这会将 DataTable 中的第一个单元格设置为 1。
回答by BlackCath
This might help someone else.
这可能会帮助其他人。
foreach (DataRowView row in dgLista.SelectedItems)
{
string text = row.Row.ItemArray[index].ToString();
}
Good luck!
祝你好运!
回答by icernos
Here's a summary of the solution.
这是解决方案的摘要。
Winform
登录
Type: System.windows.Forms.DataGridView
类型:System.windows.Forms.DataGridView
// C#
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//"Column1" = column name in DataGridView
string text = row.Cells["Column1"].value.ToString();
}
WPF equivalent
WPF 等价物
Type: DataGrid
类型:数据网格
// C#
foreach (DataRowView row in dataGrid.Items)
{
string text = row.Row.ItemArray[index].ToString();
}