user2810060
user2810060

Reputation: 11

ListBox handling in wpf application in visual studio

I have 3 listboxes,3 texboxes,3buttons in my window ,when i enter data from listbox1 into the textbox1 and click button or enter then the other 2 listbox items of same index should appear on the other 2 textboxes.

this is the code written till now

private void Get_Click(object sender, RoutedEventArgs e)
{
    int x = listbox1.SelectedIndex;
    listbox2.SelectedIndex = x;
    listbox3.SelectedIndex = x;

    ListBoxItem lb1 = (listbox1.SelectedItem as ListBoxItem);
    tb1.Text = lb1.Content.ToString();


    ListBoxItem lb2 = (listbox2.SelectedItem as ListBoxItem);
    tb2.Text = lb2.Content.ToString();

    ListBoxItem lb3 = (listbox3.SelectedItem as ListBoxItem);
    tb3.Text = lb3.Content.ToString();


}


private void Add_Click(object sender, RoutedEventArgs e)
{
    int x = listbox1.SelectedIndex;
    listbox2.SelectedIndex = x;
    listbox3.SelectedIndex = x;

    listbox1.Items.Add(tb1.Text);
    listbox2.Items.Add(tb2.Text);
    listbox3.Items.Add(tb3.Text);

}

private void Delete_Click(object sender, RoutedEventArgs e)
{
    int x = listbox1.SelectedIndex;
    listbox2.SelectedIndex = x;
    listbox3.SelectedIndex = x;

    listbox1.Items.RemoveAt(listbox1.Items.IndexOf(listbox1.SelectedItem));
    listbox2.Items.RemoveAt(listbox2.Items.IndexOf(listbox2.SelectedItem));
    listbox3.Items.RemoveAt(listbox3.Items.IndexOf(listbox3.SelectedItem));


}

Upvotes: 0

Views: 340

Answers (1)

n4m16
n4m16

Reputation: 121

It's not really clear what you're after, but I think you're trying to get the text in tb1 to be the driver instead of selecting from listbox1. I've added some simple code to the Get_Click event:

private void Get_Click(object sender, RoutedEventArgs e)
{
    foreach (ListBoxItem lbi in listbox1.Items)    //new code
    {                                              //new code
        if (lbi.Content.ToString() == tb1.Text)    //new code
        {                                          //new code
            lbi.IsSelected = true;                 //new code
            break;                                 //new code
        }                                          //new code
    }                                              //new code

    int x = listbox1.SelectedIndex;
    listbox2.SelectedIndex = x;
    listbox3.SelectedIndex = x;

    //ListBoxItem lb1 = (listbox1.SelectedItem as ListBoxItem);   //updated
    //tb1.Text = lb1.Content.ToString();                          //updated

    ListBoxItem lb2 = (listbox2.SelectedItem as ListBoxItem);
    tb2.Text = lb2.Content.ToString();

    ListBoxItem lb3 = (listbox3.SelectedItem as ListBoxItem);
    tb3.Text = lb3.Content.ToString();
}

Is this the kind of thing you're after?

Upvotes: 1

Related Questions