Winforms, creating padding when using Dock properties

后端 未结 3 2022
无人及你
无人及你 2021-01-04 01:40

How do I add padding, or some space between the textboxes when using dockstyle.top property?

for(int i =0; i< 10; i++) {
    textboxes[i] = new TextBox();         


        
相关标签:
3条回答
  • 2021-01-04 01:44

    With DockStype.Top you can't change the width of your TextBoxes, cause they are docked. You can only change the height. But to change the height of a TextBox you have to set the Multiline = true beforehand.

    To get the space between the different boxes you have to put each TextBox within a panel, set the TextBox.Dock = Fill, the Panel.Dock = Top and the Panel.Padding = 10. Now you have some space between each TextBox.

    Sample Code

    for (int i = 0; i < 10; i++)
    {
        var panelTextBox = CreateBorderedTextBox();
    
        this.Controls.Add(panelTextBox);
    }
    
    private Panel CreateBorderedTextBox()
    {
        var panel = CreatePanel();
        var textBox = CreateTextBox();
    
        panel.Controls.Add(textBox);
        return panel;
    }
    
    private Panel CreatePanel()
    {
        var panel = new Panel();
        panel.Dock = DockStyle.Top;
        panel.Padding = new Padding(5);
    
        return panel;
    }
    
    private TextBox CreateTextBox()
    {
        var textBox = new TextBox();
        textBox.Multiline = true;
        textBox.Dock = DockStyle.Fill;
    
        return textBox;
    }
    

    What i forgot, you can also give a try to the FlowLayoutPanel. Just remove the DockStyle.Top from the panels and put them into the FlowLayoutPanel. Also you should set the FlowDirection to TopDown. Maybe this can also help you to solve your problem, too.

    0 讨论(0)
  • 2021-01-04 01:46

    I know where you're coming from, this is especially frustrating after returning to WinForms from WPF.

    I would suggest using a TableLayoutPanel, in which each TextBox would get its own cell, and adjusting the properties of the cells. This should solve both your padding and size problems.

    Another alternative would be to use some more complex layout controls, such as the DevExpress ones (not free).

    0 讨论(0)
  • 2021-01-04 02:06

    Another work around that suits smaller layouts is to just add a Label control afterwards also docked to the Top, which is not AutoSized, Text=" ", Height=your padding. This is quite useful for the odd bit of padding when using the designer.

    0 讨论(0)
提交回复
热议问题