Breaking News

Editors Picks

Tuesday, July 3, 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;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ViewState["TableRow"] != null)
AddRows(Convert.ToInt32(ViewState["TableRow"]), 1);
}
}
public void AddRows(int NumberOfRowsToAdd, 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(object sender, 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.


No comments :

Post a Comment

Contact Us

Name

Email *

Message *