2

I'm trying to get a text from my ComboBox in order to switch it, but it always returns null. What am I doing wrong?

XAML:

<ComboBox Name="cbForms" SelectionChanged="cbForms_SelectionChanged" HorizontalAlignment="Left" Margin="10,289,0,0" VerticalAlignment="Top" Width="139">
    <ComboBoxItem IsSelected="True">Polygon</ComboBoxItem>
    <ComboBoxItem>Rechteck</ComboBoxItem>
    <ComboBoxItem>Dreieck</ComboBoxItem>
    <ComboBoxItem>Kreis</ComboBoxItem>
</ComboBox>

C# Code:

private void cbForms_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string text = cbForms.Text;
    switch (text)
    {
        case "Polygon":
            {
                commandText = "SELECT f.bezeichnung, t.X, t.Y, t.id FROM figure05 f, TABLE(SDO_UTIL.GETVERTICES(f.shape)) t";
                lblAnz.Content = anzPolygon.ToString();
                break;
            }

Am I missing something? Thanks for any kind of help!

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
F.Gradl
  • 39
  • 10

1 Answers1

1

This should work:

private void cbForms_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (cbForms != null)
    {
        ComboBoxItem item = cbForms.SelectedItem as ComboBoxItem;
        if (item != null && item.Content != null)
        {
            string text = item.Content.ToString();
            switch (text)
            {
                case "Polygon":
                    {
                        commandText = "SELECT f.bezeichnung, t.X, t.Y, t.id FROM figure05 f, TABLE(SDO_UTIL.GETVERTICES(f.shape)) t";
                        lblAnz.Content = anzPolygon.ToString();
                        break;
                    }
            }
        }
    }
}

If you want it to work initially before you have selected any item, you should set the SelectedIndex property of the ComboBox instead of setting the IsSelected property of the ComboBoxItem:

<ComboBox Name="cbForms" SelectionChanged="cbForms_SelectionChanged" HorizontalAlignment="Left" Margin="10,289,0,0" 
          VerticalAlignment="Top" Width="139"
          SelectedIndex="0">
    <ComboBoxItem>Polygon</ComboBoxItem>
    <ComboBoxItem>Rechteck</ComboBoxItem>
    <ComboBoxItem>Dreieck</ComboBoxItem>
    <ComboBoxItem>Kreis</ComboBoxItem>
</ComboBox>
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
mm8
  • 163,881
  • 10
  • 57
  • 88
  • But it won't work on initial selection (`item.Content` will be null while really `Polygon` item is selected). – Evk Oct 24 '17 at 10:07
  • The first call of event handler happens due to `IsSelected = true` of one of combox items. During this call `Content` is `null` probably due to way how view is constructed. This has to be handled separately I guess. Another thing: `cbForm` and `item` null-checks, they are not needed. – Sinatr Oct 24 '17 at 10:08
  • That's just a matter of setting the SelectedIndex property. See my edit. – mm8 Oct 24 '17 at 10:11