4est 4est - 4 months ago 28
C# Question

TextBox not display value after ComboBox onChange (WPF, C#, Binding)

I have UserControl contains ComboBox and TextBox:

<ComboBox x:Name="cmbId" SelectionChanged="cmbId_SelectionChanged" />
<TextBox x:Name="txb1" Visibility="Hidden" Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}" />


I have loaded values to ComboBox:

public MyDataView()
{
InitializeComponent();
MyDBViewDataContext mydata = new MyDBViewDataContext();
cmbId.ItemsSource = (from q in mydata.test_views
select q.Id).ToList();
}


When user select item on ComboBox, the TextBox should display value:

private void cmbId_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int myId = 0;
Int32.TryParse(cmbId.Text, out myId);

txb1.Visibility = Visibility.Visible;

MyDBViewDataContext myDataList = new MyDBViewDataContext();
var queryAll = (from q in myDataList.test_views
where q.Id.Equals(myId)
select q);
}


But it's not working. Something is missing or what I did wrong?

mm8 mm8
Answer Source

If both Id and FirstName are properties of your entity class, you could set the ItemsSource property of the ComboBox to an IEnumerable<YourEntityType> and bind the Text property of the TextBox to the FirstName property of the SelectedItem of the ComboBox:

public MyDataView()
{
    InitializeComponent();
    MyDBViewDataContext mydata = new MyDBViewDataContext();
    cmbId.ItemsSource = (from q in mydata.test_views
                         select q).ToList();
}

<ComboBox x:Name="cmbId" DisplayMemberPath="Id"/>
<TextBox x:Name="txb1" Visibility="Hidden" Text="{Binding Path=SelectedItem.FirstName, UpdateSourceTrigger=PropertyChanged, ElementName=cmbId}" />

Then there is no need to handle the SelectionChanged event at all.

The other option would be to actually set the Text property of the TextBox in the event handler:

txb1.Text = var queryAll = (from q in myDataList.test_views
                    where q.Id.Equals(myId)
                    select q.FirstName).FirstOrDefault();