1

I have a problem with the set of a default value for a combobox :

<ComboBox x:Name="cmbAuthentification" Height="20" Grid.Row="1" Grid.Column="1" BorderBrush="#FF2BBFF0" FontFamily="Segoe UI Light" IsReadOnly="True" SelectionChanged="cmbAuthentification_SelectionChanged">
    <ComboBoxItem>Windows</ComboBoxItem>
    <ComboBoxItem>SQL Server</ComboBoxItem>
</ComboBox>

In the xmal, I have this code :

private void cmbAuthentification_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (cmbAuthentification.SelectedIndex == 0)
    {
        txtUserID.IsEnabled = false;
        txtUserID.Clear();
        txtUserPwd.IsEnabled = false;
        txtUserPwd.Clear();
    }

    if (cmbAuthentification.SelectedIndex == 1)
    {
        txtUserID.IsEnabled = true;
        txtUserPwd.IsEnabled = true;
    }
}

When I try to set SelectedIndex="0" in the ComboBox, I have an error at runtime : NullReferenceException : Object reference not set to an instance of an object.

uvr
  • 540
  • 4
  • 11
  • 3
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – SomeBody May 04 '21 at 12:00
  • set ```SelectedIndex="0"``` in `````` and you see error solved. – NEBEZ May 04 '21 at 12:02
  • I think the error is due by txtUserID and txtUserPwd. At the selectionChanged of the cmb, the 2 elements is not know ? – Fabrice Bertrand May 04 '21 at 13:16
  • 1
    You’d better use data binding instead of event. In that way, you can bind ComboBox.SelectedItem to a property in the View-Model. – Frank May 04 '21 at 13:47

1 Answers1

0

Your issue is that the controls haven't yet been loaded when your event handler is executed for the first time.

You could check whether the value of the IsLoaded and hook up to the Loaded event if it returns false:

private void cmbAuthentification_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (!cmbAuthentification.IsLoaded)
    {
        cmbAuthentification.Loaded += (ss, ee) => cmbAuthentification_SelectionChanged(sender, e);
        return;
    }

    if (cmbAuthentification.SelectedIndex == 0)
    {
        txtUserID.IsEnabled = false;
        txtUserID.Clear();
        txtUserPwd.IsEnabled = false;
        txtUserPwd.Clear();
    }

    if (cmbAuthentification.SelectedIndex == 1)
    {
        txtUserID.IsEnabled = true;
        txtUserPwd.IsEnabled = true;
    }
}
mm8
  • 135,298
  • 10
  • 37
  • 59
  • wow ! Really thanks for that. I search a long time for that. I don't understand that code... but it works ! I'm beginner and it's hard to understand code :( – Fabrice Bertrand May 04 '21 at 16:16