简体   繁体   中英

Get value from a datagrid cell by Data Binding - wpf c#

I came with an issue trying to get the value of my currently selected row. I tried the examples from internet but they didnt work. Like: DataRowView drv = (DataRowView)clientList.SelectedItem;

What I found but couldn't figure it out how to make is how to get value through data binding. As I'm new to the whole .net and c# programming I didn't understand how to accomplish what i need. Basically in my Test.xaml.cs I need to get the Id column value to know which row of current selected row for modifying it inside the database.

<DataGridTextColumn Width="30" Header="Id" Binding="{Binding Id}"/>

UPDATED

public class DataClients
{
    public int Id { get; set; }

    public string Company { get; set; }

    public string Name { get; set; }
}

I had the same issue and have just figured it out.

Basically, your cast is wrong, I'm guessing Id is a property of a class, so you need to cast and capture your class, not the DataRowView

Client selectedClient = (Client)clientList.SelectedItem;
// This will return the instance of the class that is selected.

The reason that this works is that when you bind, each item on the grid is actually associated with its instance of the whole class, so when you get the selected item, it is returning a "Client" (I'm guessing your class is called something like that) boxed in an Object.

This is what worked for me anyway, hope this helps :).

Take a look at binding mode. Here's a little link to introduce you to this.

https://msdn.microsoft.com/en-us/library/system.windows.data.binding.mode%28v=vs.110%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM