Reputation: 49
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?
Upvotes: 0
Views: 4262
Reputation: 31394
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;
Upvotes: 0
Reputation: 5474
Assuming ItemId is in the first (0) column of the datagrid... The Selected rows will return an array so if only 1 row is selected the first (0) element would contain the row...
Try:
string strVal = DataGridView1.SelectedRows[0].Cells[0].Text;
Upvotes: 1