Tuesday, 3 July 2012

add dynamic controls(Text box, Checkbox,Dropdownlist ,Button) in asp.net


This article shows how to add rows dynamically to a Table. Example Code download adds dynamic rows with Text box, Checkbox, Dropdownlist, Button in each row.

<%@ Page Language="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%>

DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dynamically Created Controls in ASP.NETtitle>
head>
<body>
    <form id="form1" runat="server">
    <asp:Button ID="btnAddNewRow" ToolTip="Add New Row" Height="25px" runat="server"
        Text="Add New Row" OnClick="btnAddNewRow_Click" Width="110px"/>
    <br />
    <table id="table1" runat="server">
    table>
    <br />
    <br />
    <asp:Label ID="lblValues" runat="server" Font-Names="Tahoma" Font-Size="9pt">asp:Label>
    form>
body>
html>


using System;
usingSystem.Configuration;
usingSystem.Data;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.HtmlControls;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(objectsender, EventArgs e)
{
if(IsPostBack)
{
if(ViewState["TableRow"] != null)
AddRows(Convert.ToInt32(ViewState["TableRow"]), 1);
}
}
public void AddRows(intNumberOfRowsToAdd, int NumberOfCellsToAdd)
{
for (int i = 1; i <= NumberOfRowsToAdd; i++)
{
HtmlTableRow row = new HtmlTableRow();
for (int j = 1; j <= NumberOfCellsToAdd; j++)
{
HtmlTableCell cell = new HtmlTableCell();
cell.Controls.Add(new TextBox() { Width = Unit.Pixel(90), Text = "TextBox" });
cell.Controls.Add(new DropDownList() { Width = Unit.Pixel(90), });
cell.Controls.Add(new Button() { Width = Unit.Pixel(90), Text = "submit" });
cell.Controls.Add(new CheckBox() { Width = Unit.Pixel(90), Text = "CheckBox" });
row.Cells.Add(cell);
}
table1.Rows.Add(row);
}
}
protected void btnAddNewRow_Click(objectsender, EventArgs e)
{
AddRows(1, 1);
ViewState["TableRow"] = table1.Rows.Count;
}
}

Description:

Dynamic Controls have to be recreated on Page PostBack and values entered in the
Text box, Checkbox, Dropdownlist, Button  will be retained from viewstate. If we want to use Control ID to get value, we need to make sure that same control ID is used for recreating on postback. We can use a for loop to get text entered in the dynamic Text box, Checkbox, Dropdown list, Button.


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Blogger