I am trying to add Checkboxes dynamically to webpage
string[] words = masg.Split('~');
int size = words.Length;
CheckBox[] cbl = new CheckBox[size];
for (int i = 0; i < words.Length; i++)
{
cbl[i] = new CheckBox();
cbl[i].Text = words[i].ToString();
this.Controls.Add(cbl[i]);
// Response.Write("\n" + words[i]);
}
I am getting error
Control 'ctl01' of type 'CheckBox' must be placed inside a form tag with runat=server.
How should I proceed ? What changes to make on aspx page ? Please help.
You should change it to add in form, because this is referencing your Page. and any server control which you are creating programmatic or by adding on page with runat="server" should place inside a form tag.
like
this.Form.Controls.Add(cbl[i]);
or place a placeholder or panel on the form. and than you can add in it
like
placeholder1.Controls.Add(cbl[i]);
If your .aspx does not contain a form tag, then you should place a form tag there
like
<form runat="server" id="form1">
//Other mark up or server controls.
</form>
hi you need to add a parent control like Panel on your form and then add your check box controls to that panel
string[] words = masg.Split('~');
int size = words.Length;
CheckBox[] cbl = new CheckBox[size];
for (int i = 0; i < words.Length; i++)
{
cbl[i] = new CheckBox();
cbl[i].Text = words[i].ToString();
pnlControls.Controls.Add(cbl[i]);
// Response.Write("\n" + words[i]);
}
Add the a panle control in your aspx page :
<asp:Panel ID="pnlControls" runat="server" >
Related
I have created a panel in my page view (tour.aspx file).
Now I want to access it in my class file (add_tour.cs file).
This is my panel:
<asp:Panel ID="itinerary_panel" runat="server"></asp:Panel>
This is my code behind tour.aspx file:
add_tour tour_obj = new add_tour();
int days_count = 2;
tour_obj.textbox_generator(days_count);
And this code is in add_tour.cs file:
public void textbox_generator(int days_count)
{
}
Now how to access the panel from aspx file?
Please help.
There's no need to actually add the text boxes to the panel from this class.
public List<TextBox> textbox_generator(int days_count)
{
var textBoxes = new List<TextBox>();
for(int i = 0; i < days_count; i++)
{
txt_desc = new TextBox();
txt_desc.ID = "txt_desc" + i.ToString();
txt_desc.CssClass = "form-control";
txt_desc.Attributes.Add("placeholder", "Enter day " + i + " description");
txt_desc.TextMode = TextBoxMode.MultiLine;
textBoxes.Add(txt_desc);
}
return textBoxes;
}
Then change your code behind to:
add_tour tour_obj = new add_tour();
int days_count = 2;
var textBoxes = tour_obj.textbox_generator(days_count);
foreach(var textBox in textBoxes)
{
itinerary_panel.Controls.Add(textBox);
}
Note that you need to be careful where you add these controls in the page lifecycle. See Microsoft documentation.
This keeps your textbox_generator from needing to know anything about the specific page using it.
Also, you should really align your naming conventions with C# standards. Use PascalCasing. textbox_generator should be TextBoxGenerator etc. And you can probably make textbox_generator into a static method if it doesn't need to access any fields or properties of its class.
If you really wanted your other class to itself add the controls directly to the panel, then you would just pass a reference to the panel from the code behind to the class.
public void textbox_generator(int days_count, Panel panel)
{
for(int i = 0; i < days_count; i++)
{
txt_desc = new TextBox();
txt_desc.ID = "txt_desc" + i.ToString();
txt_desc.CssClass = "form-control";
txt_desc.Attributes.Add("placeholder", "Enter day " + i + " description");
txt_desc.TextMode = TextBoxMode.MultiLine;
panel.Controls.Add(txt_desc);
}
}
and call this this way from your code behind:
add_tour tour_obj = new add_tour();
int days_count = 2;
var textBoxes = tour_obj.textbox_generator(days_count, itinerary_panel);
This works because itinerary_panel actually is a reference to the panel. See Passing Objects By Reference or Value in C#. However, it's often a bad idea to have a method modify the state in that manner.
I have an update panel, which fires every third seconds. I have this code into my asp.net page
<div ID="campaignDiv" runat="server" >
<ul>
</ul>
</div>
and I add its content dynamically like this:
private string CreateLiCheckbox(string checkBoxText)
{
return string.Format("<li><span class=\"textDropdown\">{0}</span><input id=\"{1}\" value=\"{0}\" type=\"checkbox\"><label for=\"{1}\"></label></li>", checkBoxText, checkBoxText + "dropdownID");
}
if (!IsPostBack) {
List<string> comps = getCompainNames();
string html = "<ul>";
for (int i = 0; i < comps.Count(); i++) {
html = html + CreateLiCheckbox(comps[i]);
}
html = html + "</ul>";
campaignDiv.InnerHtml = html;
}
My problem
when the page loads, the checkboxes are like this:
Then, I change the values to these:
but when the update pannel works, the page returns to its default statues, where nothing of the checkboxes are selected
could you help please?
I have this code:
var myArray = new Array();
var counter = 0;
function addElementToForm(value){
counter ++;
if (counter < 10)
{
$("#cheese").append(value + '<input type="number" value="0"><br />');
myArray.push(counter + value);
}
};
I have an ASP.NET form on the same page, in the same action of the sumbit button for the form, I want to be able to access myArray from the codefile as well!!
Take a hidden control and make it as runat="server" and try to keep the array value in the hidden control and access it from the codebehind file.
I get that error when trying to generate a number of buttons programmatically. I have no ctl02.. Why do i get that mistake?
Button pgs = new Button();//Create New Topic
pgs.Width = 20;
pgs.Command += obtainTopicsPerPage_Click;
pgs.CommandName = tPage.ToString();
pgs.Text = tPage.ToString();
btns.Add(tPage.ToString());
buttons.Add(pgs);
I create a few buttons and loop through the list (buttons). Then i get that mistake :(. ... why?
Full design:
int maximumTopicPages;
int tPage;
int questionNumber=1;
Dictionary<string, List<DisplayAllQuestionsTable>> tPages;
List<Button> buttons = new List<Button>();
protected void Answer_Click(object sender, EventArgs e)
{
ViewState["SeekPressed"] = "pressed";
tPages = new Dictionary<string, List<DisplayAllQuestionsTable>>();
string subTopic = SubTopicDropDownList.SelectedItem.Value;
List<DisplayAllQuestionsTable> threadsByTopic = new List<DisplayAllQuestionsTable>();
List<string> btns = new List<string>();
foreach (var topicKeys in postsByTopic)
{
if (topicKeys.Key == subTopic)
{
foreach (var item in postsByTopic[topicKeys.Key])
{
questionNumber++;
maximumTopicPages++;
threadsByTopic.Add(item);//Adds All DisplayAllTables objects
//if there are 20 add a button.
if (maximumTopicPages == 20)
{
tPages.Add(tPage++.ToString(), threadsByTopic);//Add a number to the page each time, with a DisplayTable object
//new Button
Button pgs = new Button();//Create New Topic
pgs.Width = 20;
pgs.Command += obtainTopicsPerPage_Click;
pgs.CommandName = tPage.ToString();
pgs.Text = tPage.ToString();
btns.Add(tPage.ToString());
buttons.Add(pgs);
maximumTopicPages = 0;
threadsByTopic.Clear();
}
}//number of questions per page
if (!tPages.ContainsKey((questionNumber / 20).ToString()))
{
tPages.Add((questionNumber / 20).ToString(), threadsByTopic);//If A button is missing add it.
}
}
Way the buttons are added to the table:
void MyButtonTable()
{
TableRow myTableRow = new TableRow();
HtmlForm form = new HtmlForm();
form.Attributes.Add("runat", "server");
Page.Controls.Add(form);
foreach (var item in buttons)
{
TableCell myTableCell = new TableCell();
form.Controls.Add(item);
myTableCell.Controls.Add(item);
myTableRow.Cells.Add(myTableCell);
}
Table2.Rows.Add(myTableRow);
Page.Controls.Add(Table2);
}
Are you adding your buttons to the Page afterwards?
Also, if you do not specify an ID to your buttons, they will be given one automatically in the form of ctlXXX
What is in the .aspx file? Specifically, what is the 'buttons' control? My guess is, it is a placeholder or panel or something similar. In that case, you need to add this to your .aspx file:
...
<body>
<form runat="server">
...
</form>
</body>
...
That should fix it.
ASP.NET needs to have the <form> tag managed by the server in order to use server side controls on your page. If your page already has a <form> tag on it somewhere, you can just add runat="server" to that tag and it will fix it. (That assumes the 'buttons' control that you're trying to add the dynamically created button into -- the placeholder or panel or whatever -- is itself between the <form>...</form> tags.)
Its working....
Please add your new button control into from
protected void btnsubmit_Click(object sender, EventArgs e)
{
Button objButton = new Button();
objButton.Text = "New Button";
objButton.ID = "randomButton";
form1.Controls.Add(objButton);
}
Here form1 -> form name available into .aspx file and objButton is button object.
You have to check if "buttons" (I think is a placeholder) is inside a div or a tag with runat="server"
update
If I understand you can try something like this:
HtmlForm form = new HtmlForm();
form.Attributes.Add("runat", "server");
form.Controls.Add(buttons);
Page.Controls.Add(form);
(untested)
I have an UpdatePanel and in it a regular Panel. In the Panel I dynamically add simple UserControls. The Usercontrol has a Button and a Label. When I click on a button in a control it removes all controls in the Panel which I have added dynamically.
Can anyone help?
int controlID = 0;
List<Control> cc = new List<Control>();
if (Session["ControlsCompleted"] != null)
{
cc = Session["ControlsCompleted"] as List<Control>;
for (int i = 0; i < cc.Count; i++)
{
pnlCompletedEducation.Controls.Add(cc[i]);
}
controlID = cc.Count;
}
Controls_TestWebUserControl ct = LoadControl(#"Controls\TestWebUserControl.ascx") as Controls_TestWebUserControl;
ct.ID = controlID.ToString();
cc.Add(ct);
ct.EnableViewState = true;
pnlCompletedEducation.Controls.Add(ct);
txtInstitutionName.Text = controlID.ToString();
List<Control> lc = new List<Control>();
for (int i = 0; i < pnlCompletedEducation.Controls.Count; i++)
{
lc.Add(pnlCompletedEducation.Controls[i]);
}
Session["ControlsCompleted"] = lc;
This is how I add the controls to the panel. I had to keep them somewhere, and i couldn't do it with the ViewState, so i used a Session, which is a bad idea.
You say that you are adding the user control dynamically. Are you having code like this:
void Page_Load(...)
{
if (!IsPostback)
// AddUserControl here.
}
You need to add the user control during every request, also postbacks, because it will not be stored in the view state that you have modified the control tree.
You problem that you have not recreated (for example at Page_Load) dynamically added control.
Make sure that control is recreated on IsPostBack