如何读取Datagrid选定行中的第一个单元格中的值? [英] How to read the value in the first cell in a selected row of a Datagrid?

查看:127
本文介绍了如何读取Datagrid选定行中的第一个单元格中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个datagrid,它包含来自两个不同表的数据,称为ITEMS和ORDER_ITEMS。
datagrid的格式是这样的 -
Item ID |项目名称|单价|数量|金额



这里列ItemID,ItemName,Price属于表ITEMS,列数量和金额(amount = price * quantity)属于表ORDER_ITEMS。



所以我在将所选行创建为ITEMS类型的新对象(或实例)以捕获ItemID时遇到问题。如何读取选择行的ItemID属性?






更新:
当我尝试使用以下代码(根据John K.给出的语法),我得到错误 - 错误1'Microsoft.Windows.Controls.DataGrid'不包含'SelectedRows'的定义,没有扩展方法'SelectedRows'可以找到类型为Microsoft.Windows.Controls.DataGrid的第一个参数(您是否缺少using指令或程序集引用?)

  string id = selectedItemsGrid.SelectedRows [0] .Cells [0] .Text; 

我发现有关问题的一些信息。刚刚在Microsoft Library中找到它在命名空间System.Windows.Forms.dll中。但我现在正在使用Windows Presentation Foundation。你认为这与我目前面临的问题有关吗?

解决方案

使用DataGrid.CurrentItem属性。这将给你绑定到当前行的数据的对象。所以例如:

  class DataClass {
string ID {get;组; }
...
}

...

DataClass current =(DataClass)dataGrid.SelectedItem;
string id = current.ID;


I have a datagrid which contains data from two different tables called ITEMS and ORDER_ITEMS. The datagrid's format is like this - Item ID | Item Name | Unit Price | Quantity | Amount

Here, the columns ItemID, ItemName, Price belong to the table ITEMS and the columns Quantity and Amount (amount = price*quantity) belong to the table ORDER_ITEMS.

So I am having some problem with creating the selected row as a new object (or instance) of ITEMS type to catch the ItemID. How can I read the ItemID attribute of the 'selected' row?


Update: When I tried use the following code (as per the syntax given by John K.), I got the error - Error 1 'Microsoft.Windows.Controls.DataGrid' does not contain a definition for 'SelectedRows' and no extension method 'SelectedRows' accepting a first argument of type 'Microsoft.Windows.Controls.DataGrid' could be found (are you missing a using directive or an assembly reference?)

     string id = selectedItemsGrid.SelectedRows[0].Cells[0].Text;

I found some info about the problem. Just found in the Microsoft Library that it is in the namespace System.Windows.Forms.dll. But I'm using Windows Presentation Foundation now. Do you think it's related to the problem I'm currently facing?

解决方案

Use the DataGrid.CurrentItem property. That give you the object that is data bound to the current row. So for example:

class DataClass {
   string ID { get; set; }
   ...
}

...

DataClass current = (DataClass)dataGrid.SelectedItem;
string id = current.ID;

这篇关于如何读取Datagrid选定行中的第一个单元格中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆