Search code examples
c#asp.nettextboxalignment

set padding to dynamic textbox C# asp.net


here is the code I create textbox from C# code..

for (int x = 0; x < 30; x++)
            {
                            TextBox txt = new TextBox();
                            txt.ID = "txt - " + x.ToString(); 
                            data.Controls.Add(txt);
                            data.Controls.Add(new LiteralControl("<br/>"));
             }

all textbox will be stick to each other.. I wonder can I add padding-top in the loop? how may I do it?

thanks for your help and your suggestion and comment is appreaciated.

This is create by using C# enter image description here

I wish want got space like this. enter image description here

please ignore the drop down box.. its just example.


Solution

  • I hope you know something about CSS and stylesheets? You can render anything you want in the backend like in your example: textboxes. Using CSS you can add some style to it. This doesn't needs to be done during the creation of your controls.

    In your example just create a stylesheet like default.css and add it into your page using:

    <link rel="stylesheet" type="text/css" href="./css/default.css" />
    

    Then using following code you can add some padding or even better some margin to your inputs:

    input[type="text"] {
        margin-bottom: 10px;
    }
    

    Another solution is using classes:

    ASP.NET

    for (int x = 0; x < 30; x++)
    {
         TextBox txt = new TextBox();
         txt.ID = "txt - " + x.ToString(); 
         txt.CssClass = "form-control"; //Assign a css class to your textbox
         data.Controls.Add(txt);
         data.Controls.Add(new LiteralControl("<br/>"));
    }
    

    CSS

    .form-control {
        margin-bottom: 10px;
    }