Crude Operations using RunTime TextBoxes Controls in Asp.net

Crude Operations using RunTime TextBoxes Controls in Asp.net

Sometimes we need to create text boxes on runtime on button click
and store the values from runtime textboxes in Asp.net
.aspx Page————————————————————————

<asp:Panel ID=”pnlMain” runat=”server” Style=”padding-left: 10px;”>

</asp:Panel>
.aspx.cs Page————————————————————————

if (!Page.IsPostBack)
{

ViewState[“NumberOfControls”] = NumberOfControls = 0;
}
else
{
this.createControls();

}
protected int NumberOfControls
{
get { return (int)ViewState[“NumControls”]; }
set { ViewState[“NumControls”] = value; }
}
private void createControls()
{
int count = (int)ViewState[“NumberOfControls”];

for (int i = 0; i < count; i++)
{
TextBox tx = new TextBox();
tx.ID = “ControlID_” + i.ToString();
//Add the Controls to the container of your choice
pnlMain.Controls.Add(tx);
}
}

//Call this function on button event to create control
// It create 4 TextBoxes at a time
private void addSomeControl()
{
for (int a = 0; a < 4; a++)
{
TextBox tx = new TextBox();
NumberOfControls = (int)ViewState[“NumberOfControls”];
tx.ID = “ControlID_” + NumberOfControls.ToString();

pnlMain.Controls.Add(tx);
NumberOfControls++;
ViewState[“NumberOfControls”] = NumberOfControls;
}

}

//IF want to display dynamic on runtime Controls then use below code

private void LoadData()
{
DataSet ds = objUpdatCont.ViewProfile(Convert.ToInt32(userid));
int rowcount = ds.Tables[0].Rows.Count;
ViewState[“NumberOfControls”] = rowcount;
for (int i = 0; i < rowcount; i++)
{

TextBox tx = new TextBox();
//NumberOfControls = (int)ViewState[“NumberOfControls”];
tx.ID = “ControlID_” + i.ToString();

pnlMain.Controls.Add(tx);
}
}
//IF want to insert data on table using runtime Controls then use below code

private void SaveData()
{
NumberOfControls = (int)ViewState[“NumberOfControls”];
for (int i = 0; i < NumberOfControls; i++)
{
string txtvalue = “ControlID_” + i.ToString();
TextBox txt = (TextBox)pnlMain.FindControl(txtvalue);
if (txt != null)
{
string=txt.Text;
}
}
}

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply