<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Design.aspx.cs" Inherits="WebApplication1.Design" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Read Dynamic Control Value" OnClick="Button1_Click" />
<br />
<asp:GridView ID="GridView1" runat="server" GridLines="Both" CellPadding="4" ForeColor="#333333">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</div>
</form>
</body>
</html>
Step 2: - Design.aspx.cs
protected void Page_Init(object sender, EventArgs e)
{
GenerateDynamicControl(5);
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("DynamicTextBoxValue", typeof(string));
DataRow dr = null;
foreach (Control control in Panel1.Controls)
{
//Find table
if (control is Table)
{
Table table = (Table)control;
foreach (Control tableRow in table.Controls)
{
//Find table row
if (tableRow is TableRow)
{
TableRow tRow = (TableRow)tableRow;
foreach (Control tableCell in tRow.Controls)
{
//Find table cell
if (tableCell is TableCell)
{
TableCell tCell = (TableCell)tableCell;
foreach (Control ctrl in tCell.Controls)
{
dr = dt.NewRow();
//Find Label in cell
if (ctrl is Label)
{
Label label = (Label)ctrl;
}
//Find TextBox in cell
if (ctrl is TextBox)
{
TextBox textBox = (TextBox)ctrl;
dr["DynamicTextBoxValue"] = textBox.Text;
dt.Rows.Add(dr);
}
}
}
}
}
}
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
private void GenerateDynamicControl(int rowsCount)
{
Table table = new Table();
table.ID = "Table1";
//Page.Form.Controls.Add(table);
Panel1.Controls.Add(table);
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
TableCell cellLabel = new TableCell();
Label lb = new Label();
lb.ID = "LabelRow_" + i;
lb.Text = "LabelRow_" + i;
cellLabel.Controls.Add(lb);
row.Cells.Add(cellLabel);
TableCell cellTextBox = new TableCell();
TextBox tb = new TextBox();
tb.ID = "TextBoxRow_" + i;
tb.Text = i.ToString();
cellTextBox.Controls.Add(tb);
row.Cells.Add(cellTextBox);
table.Rows.Add(row);
}
}
Output
No comments:
Post a Comment