How to add textbox control dynamically in runtime in WPF using c#

后端 未结 2 850
猫巷女王i
猫巷女王i 2021-01-29 04:00

I am new in WPF.I want to create 3 textbox for each row at runtime when i click generate button. please help me.

Automatically created textbox

 **Code b         


        
2条回答
  •  感动是毒
    2021-01-29 04:57

    Just give your grid a name in xaml :

    
        
    
    

    and in code behind :

    private void btnGenerate_Click(object sender, RoutedEventArgs e)
    {
        //Get the number of input text boxes to generate
        int inputNumber = Int32.Parse(textBoxInput.Text);
    
        //Initialize list of input text boxes
        inputTextBoxes = new List();
    
        //Generate labels and text boxes
        for (int i = 1; i <= inputNumber; i++)
        {
            //Create a new label and text box
            Label labelInput = new Label();
            Grid1.Children.Add(labelInput);
            TextBox textBoxNewInput = new TextBox();
            Grid1.Children.Add(textBoxNewInput);
        }
    }
    

    If you want, you can set the position also so that the newly created elements doesn't overlap each other.

    EDIT :

    You need to create a grid with required rows and columns and then place each textbox or label inside the required row-column combination. It contains 6 rows and 3 columns. Please see the example below :

    
        
            
            
            
            
            
            
        
        
            
            
            
        
     
    
    private void btnGenerate_Click(object sender, RoutedEventArgs e)
    {
        //Get the number of input text boxes to generate
        int inputNumber = Int32.Parse(textBoxInput.Text);
    
        //Initialize list of input text boxes
        inputTextBoxes = new List();
    
        //Generate labels and text boxes
        for (int i = 1; i <= inputNumber; i++)
        {
            //Create a new label and text box
            Label labelInput = new Label();
    
            Grid.SetColumn(labelInput, i);
            Grid.SetRow(labelInput, i);
            Grid1.Children.Add(labelInput);
    
            TextBox textBoxNewInput = new TextBox();
            Grid.SetColumn(labelInput, i+1);
            Grid.SetRow(labelInput, i);
            Grid1.Children.Add(textBoxNewInput);
        }
    }
    

提交回复
热议问题