1
votes

I have a Button in wpf. if i click the button, it will create a row with 3 columns in grid. 1st column has ComboBox with 3 items. Item1,Item2 and Item3. 2nd column has no Control.3rd column has Textbox control.

If combobox item value checked is Equal to item3, then i need to add a Textbox control to the 2nd column of the grid to the same row. i have the code to add those controls. but i dont know how to add the Textbox for the particular checkboxItem3 row in run time.

note: checkbox value can check at anytime. even if i check at run time, it has to create new textbox for the respective row's 2nd column.

this is my code.

public int count = 1;
    private void btn_add_Click(object sender, RoutedEventArgs e)
    {
        //Creating Rows..
        RowDefinition row0 = new RowDefinition();
        row0.Height = new GridLength(30);
        grid2.RowDefinitions.Add(row0);

        //Creating columns..
        ColumnDefinition col0 = new ColumnDefinition();
        ColumnDefinition col1 = new ColumnDefinition();
        ColumnDefinition col2 = new ColumnDefinition();
        col0.Width = new GridLength(100);
        col1.Width = new GridLength(100);
        col2.Width = new GridLength(100);
        grid2.ColumnDefinitions.Add(col0);
        grid2.ColumnDefinitions.Add(col1);
        grid2.ColumnDefinitions.Add(col2);

        int i = count;

        //1st Column Combobox
        ComboBox cmb = new ComboBox();
        cmb.Items.Add("item1");
        cmb.Items.Add("item2");
        cmb.Items.Add("item3");
        Grid.SetRow(cmb, i);
        Grid.SetColumn(cmb, 0);
        grid2.Children.Add(cmb);

        //3rd column Textbox 
        TextBox txt = new TextBox();
        Grid.SetRow(txt, i);
        Grid.SetColumn(txt, 2);
        grid2.Children.Add(txt);
        count++;
    }
1

1 Answers

0
votes

You can use ComboBox's Tag property to store row information :

ComboBox cmb = new ComboBox();
......
......
//give the combobox a tag so you can identify...
//the row number of this combobox later
cmb.Tag = i;
//attach event handler
cmb.SelectionChanged += cmb_SelectionChanged;

Then in the event handler method, you can easily add new TextBox in the correct Grid row, for example :

void cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if(e.AddedItems[0].ToString() == "item3")
    {
        var txt = new TextBox();
        var row = (int)((ComboBox)sender).Tag;
        Grid.SetRow(txt, i);
        Grid.SetColumn(txt, 1);
        grid2.Children.Add(txt);
    }
}