Search code examples
c#wpflinqdatagrid

Get cell values from DataGrid


I have a DataGrid what is populated with data from a join.

private void GetTeamData()
{
    DataContext dc = new DataContext(connString);
    Table<Team> tblLag = dc.GetTable<Team>();
    Table<Division> tblDivision = dc.GetTable<Division>();

    var teams = from team in tblLag
                join division in tblDivision on team.Division equals division.Id
                select new
                {
                    name = team.TeamName,
                    beliggenhet = team.Location,
                    arena = team.Arena,
                    division = division.Name
                };

    dgTeams.ItemsSource = teams;
}

I want to get the data from the selected row and place it in different textboxes. After a lot of frustrating googling and trying i finaly find a solution what works:

private void ShowSelectedTeam(Object sender, RoutedEventArgs args)
{
    GetDivisionNames();
    dgTeams.SelectionUnit = DataGridSelectionUnit.FullRow;
    Object selectedTeam = dgTeams.SelectedItem;

    List<PropertyInfo> props = new List<PropertyInfo>(selectedTeam.GetType().GetProperties());

    tbxTeam.Text = props[0].GetValue(selectedTeam, null).ToString();
    tbxBeliggenhet.Text = props[1].GetValue(selectedTeam, null).ToString();
    tbxArena.Text = props[2].GetValue(selectedTeam, null).ToString();
    cbxDivisions.Text = props[3].GetValue(selectedTeam, null).ToString();
}

The problem is that this is a pretty complicated way to do something what shouldn't need to be that difficult. I would be glad for suggestions for a more simplistic code.


Solution

  • Create a type that holds the name, beliggenhet , arena and division properties:

    public class YourType
    {
        public string Name { get; set; }
        public string Beliggenhet { get; set; }
        public string Arena { get; set; }
        public string Division { get; set; }
    }
    

    Set the ItemsSource to an IEnumerable<YourType>:

    var teams = from team in tblLag
                    join division in tblDivision on team.Division equals division.Id
                    select new YourType
                    {
                        Name = team.TeamName,
                        Beliggenhet = team.Location,
                        Arena = team.Arena,
                        Division = division.Name
                    };
    

    And cast the SelectedItem property to your type:

    YourType selectedTeam = dgTeams.SelectedItem as YourType;
    if (selectedTeam != null)
    {
        tbxTeam.Text = selectedTeam.Name;
        tbxBeliggenhet.Text = selectedTeam.Beliggenhet;
        ...
    }