How to generate dynamic TextBoxes based on count selected in DropDownList in ASP.Net

Last Reply on Aug 12, 2014 03:35 AM By Azim

Posted on Aug 11, 2014 08:46 PM

Is there a way I could get the DropDownList Item Count then output it on the dynamic textboxes whose count is based on dropdownlist count. Lets say My item in Dropdown is 3. then 3 TextBox is autogenerated. Then I Want my textbox "Text" to be 1,2,3 since the items are 3 on dropdown. Can someone help me on this?

 

You are viewing reply posted by: Azim on Aug 12, 2014 03:35 AM.
Posted on Aug 12, 2014 03:35 AM

You can use Repeater for this.

HTML

<div>
    Numbers of TextBox
    <asp:DropDownList ID="ddlNumberOfRows" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlNumberOfRows_SelectedIndexChanged">
        <asp:ListItem Text="One" Value="1" />
        <asp:ListItem Text="Two" Value="2" />
        <asp:ListItem Text="Three" Value="3" />
    </asp:DropDownList>
    <br />
    <br />
    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
            <%#Container.ItemIndex+1 %>
            <asp:TextBox ID="txtTextBox1" runat="server" />
        </ItemTemplate>
        <SeparatorTemplate>
            <br />
        </SeparatorTemplate>
    </asp:Repeater>
</div>

 C#

protected void ddlNumberOfRows_SelectedIndexChanged(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("TextBox");
    int count = Convert.ToInt32(ddlNumberOfRows.SelectedItem.Value);
    for (int i = 0; i < count; i++)
    {
        dt.Rows.Add("");
    }
    this.Repeater1.DataSource = dt;
    this.Repeater1.DataBind();
}

Screenshot