Now Updated code is this :
protected void ddlIds_SelectedIndexChanged(object sender, EventArgs e)
{
switch (ddlIds.SelectedItem.Text)
{
case "Textbox":
var txtBox = string.Empty;
if (hdnValue.Value != "" && hdnValue.Value.Contains("txtBox"))
{
var value = hdnValue.Value.Split('^');
int latestID = CountStringOccurrences(hdnValue.Value, "txtBox") + 1;
txtBox = "txtBox" + latestID.ToString();
hdnValue.Value = hdnValue.Value + "^" + txtBox;
}
else
{
txtBox = "txtBox1";
hdnValue.Value = hdnValue.Value + "^" + txtBox;
}
break;
case "CheckBox":
var chkbox = string.Empty;
if (hdnValue.Value != "" && hdnValue.Value.Contains("chkBox"))
{
var value = hdnValue.Value.Split('^');
int latestID = CountStringOccurrences(hdnValue.Value, "chkBox") + 1;
chkbox = "chkBox" + latestID.ToString();
hdnValue.Value = hdnValue.Value + "^" + chkbox;
}
else
{
chkbox = "chkBox1";
hdnValue.Value = hdnValue.Value + "^" + chkbox;
}
break;
}
if (hdnValue.Value != "")
{
var val = hdnValue.Value.Split('^');
foreach (var IDs in val)
{
if (IDs.Contains("chk"))
{
CheckBox chkBox = new CheckBox();
chkBox.ID = IDs;
Panel1.Controls.Add(chkBox);
}
else if (IDs.Contains("txt"))
{
TextBox TxtBox = new TextBox();
TxtBox.ID = IDs;
Panel1.Controls.Add(TxtBox);
}
}
}
}
Handle the control in post back
This function I have used from link ttp://www.dotnetperls.com/string-occurrence
public static int CountStringOccurrences(string text, string pattern)
{
int count = 0;
int i = 0;
while ((i = text.IndexOf(pattern, i)) != -1)
{
i += pattern.Length;
count++;
}
return count;
}
Marked it as solution if you like it