Skip to content Skip to sidebar Skip to footer

Wpf: Get Column Name From Selected Row

I am trying to get the Row's particular column from selected item in wpf from DataGrid. Name of DataGrid is Datagrid_Newsale. I am getting alert of whole row when it is selected, S

Solution 1:

You will have to bind the ItemsSource of DataGrid to CustomerDetails collection in order to get CustomDetails in SelectedItem.

Create property in your viewmodel (if using MVVM) or in code behind like

List<CustomerDetails> customerDetails = new List<CustomerDetails>();
    List<CustomerDetails> MyCollection
    {
        get
        {

            return myList;
        }
        set
        {
            myList = value;
            PropertyChanged(this, new PropertyChangedEventArgs("MyCollection"));
        }
    }

and in xaml just do.

<DataGridItemsSource="{Binding MyCollection}"/>

OR if you are directly filling the Items in the datagrid add instances of CustomerDetails like

dataGrid.Items.Add(newCustomerDetails(){Name = "abc"}, xyz propertis)

Thanks

Solution 2:

If you can access the grid from your selection event then following should give your the column ((DataGrid)sender).CurrentCell.Column.Header

and use some mapping for the column name to the property of the object your want to show

Solution 3:

I came up with this easy solution.

Mapped datatype of copyitem that was Anonymous in my case. In this case using Dynamic datatype solved my problem.

Due to my data was coming dynamically and then i was trying to map out particular column, so it was not really possible to do it statically because there is not data then.

Using Dynamic Datatype-

dynamic copyitem = dataGrid1.SelectedItem;

Accessing property-

int localId = copyitem.ID;

furthermore for customerName,TotalAmount i did the same.

Linq Query changes-

var query= (fromorderin db.Customer
whereorder.ID=localId
selectorder).ToList();

DataGrid_OpenSale.ItemsSource=query // returning data to another datagrid.

Solution 4:

in VB ⠀⠀⠀

PrivateSub SCUSTDataGrid_GotFocus(sender AsObject, e As RoutedEventArgs) Handles SCUSTDataGrid.GotFocus
  Dim og As DataGridCell = e.OriginalSource
  Dim ccontent As TextBlock = og.Content
  Dim dg As DataGrid
  dg = e.Source
  Dim selcol AsString = dg.CurrentCell.Column.Header.ToString

  MessageBox.Show(selcol.ToString + ccontent.Text + " got focus event")
EndSub

Post a Comment for "Wpf: Get Column Name From Selected Row"