PnP
PnP

Reputation: 3185

C# Access object via variable name

Explaining with my code will be infinitely easier, so;

    private void dtSelectorLoad_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(dtSelector.SelectedValue != null ? dtSelector.SelectedValue.ToString() : "I have 0 selected items!");
        var query =
        from obj in dataEntities.someTable
        select obj;
        primaryDataGrid.ItemsSource = query.ToList();

    }

Essentially, based on the value of the dtSelector.SelectedValue.ToString(); I need to execute the from obj in dataEntities.someTable where someTable is the value of dtSelector.SelectedValue.ToString();.

How can I achieve this? Banging my head against the wall here. End-game is that when the user clicks the button, it populates a dataGrid with data from the table currently selected in the listBox.

Upvotes: 0

Views: 112

Answers (1)

Blindy
Blindy

Reputation: 67487

The reason why it seems impossible (it isn't) is because what you're doing goes against every single programming and database principle. In particular, relational databases are made to be queried on field condition, not split between multiple tables with identical schemas, and I'll be honest with you, if you did that working for me, you'd be fired by the end of the day.

However, if you insist on this you have two options:

  1. Reflection gives you access to properties based on their name. Congratulations, you brought SQL injection to WinForms in general.

  2. A simple switch statement on all possible values, which forwards the request to the correct table. Of course this isn't exactly scalable to new values, since you have to recompile your code to add the new values, but at this point we're throwing any kind of professionalism out the window.

Upvotes: 2

Related Questions