Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data from selected row in Gridview in C#, WPF

Tags:

c#

xaml

gridview

I am trying to retrieve data from a Gridview that I have created in XAML.

<ListView Name="chartListView" selectionChanged="chartListView_SelectionChanged">
  <ListView.View>
     <GridView>
        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="250"/>
        <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Type}" Width="60"/>
        <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" Width="100"/>
     </GridView>
  </ListView.View>
</ListView>

I have seen some code like this :-

GridViewRow row = GridView1.SelectedRow;
TextBox2.Text = row.Cells[2].Text;

However my problem is that my GridView is created in XAML, and is not named, ie I cannot (or do not know how to) create a reference to 'gridview1', and therefore cannot access objects within it.

Can I name or create a reference to my gridview either from c# or XAML so I can use the above code?

Secondly, can I then access the array elements by name instead of index, something like :-

TextBox2.Text = row.Cells["ID"].Text

Thanks for any help.

like image 439
Will Avatar asked Nov 28 '25 20:11

Will


2 Answers

You're doing something horribly wrong. You should not be trying to read data from grid cells, but from your business objects directly. And you should avoid procedural code when a pure XAML solution exists:

<TextBox x:Name="TextBox2" Text={Binding SelectedItem.ID, ElementName=chartListView}"/>

WPF is not intended to be used like you're trying to. So reading individual grid cells is a dirty hack. That said, it goes something like this:

string UglyHack(string name)
{
    var columns = (chartListView.View as GridView).Columns;
    int index = -1;
    for (int i = 0; i < columns.Count; ++i)
    {
        if ((columns[i].Header as TextBlock).Text == name)
        {
            index = i;
            break;
        }
    }
    DependencyObject j = SelectedListView.ItemContainerGenerator.ContainerFromIndex(SelectedListView.SelectedIndex);
    while (!(j is GridViewRowPresenter)) j = VisualTreeHelper.GetChild(j, 0);
    return (VisualTreeHelper.GetChild(j, index) as TextBlock).Text;
}
like image 67
CannibalSmith Avatar answered Nov 30 '25 10:11

CannibalSmith


Yes you can name your gridview:

<GridView x:Name="chartGridView">
    ...
</GridView>

Make sure the following is included in the Window definition:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

This will enable you to reference it from your c# code.

like image 24
ChrisF Avatar answered Nov 30 '25 11:11

ChrisF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!