I am creating an application where I require to add dynamic checkbox list. Please anyone tell me how to add dynamic checkbox list using C#.
Put a placeHolder on your form with the ID placeHolder and add the following code to your Page_Load():
CheckBoxList cbList = new CheckBoxList();
for (int i = 0; i < 10; i++)
cbList.Items.Add(new ListItem("Checkbox " + i.ToString(), i.ToString()));
placeHolder.Controls.Add(cbList);
This will add 10 CheckBox objects within your CheckBoxList(cbList).
Use the following code to examine each CheckBox object within the CheckBoxList
foreach(ListItem li in cbList.Items)
{
var value = li.Value;
var text = li.Text;
bool isChecked = li.Selected;
}
The placeholder is used to add the CheckBoxList to the form at runtime, using a placeholder will give you more control over the web page where the CheckBoxList and its items will appear.
Here is an example
CheckBoxList chkList = new CheckBoxList();
CheckBox chk = new CheckBox();
chkList.ID = "ChkUser";
chkList.AutoPostBack = true;
chkList.RepeatColumns = 6;
chkList.DataSource = us.GetUserDS();
chkList.DataTextField = "User_Name";
chkList.DataValueField = "User_Id";
chkList.DataBind();
Panel pUser = new Panel();
if (pUserGrp != "")
{
pUser.GroupingText = pUserGrp ;
chk.Text = pUserGrp;
}
else
{
pUser.GroupingText = "Non Assigned Group";
chk.Text = "Non Assigned group";
}
pUser.Controls.Add(chk);
pUser.Controls.Add(chkList);
this.Form.Controls.Add(pUser);
At code behind you can create new ASP.NET Controls and you can add these controls to your page. All you need to do is to create new CheckBoxList Object and add ListItems to it. Finally, you need to add your CheckBoxList to your Page.
// Create CheckBoxList
CheckBoxList list= new CheckBoxList();
// Set attributes for CheckBoxList
list.ID = "CheckBoxList1";
list.AutoPostBack = true;
// Create ListItem
ListItem listItem = new ListItem();
// Set attributes for ListItem
listItem .ID = "ListItem1";
// Add ListItem to CheckBoxList
list.Items.Add(listItem );
// Add your new control to page
this.Form.Controls.Add(list);
Related
I am pretty new in .NET* and **SharePoint and I have the following problem.
I am developing a Web Part (into Share Point 2013) that retrieve n SharePoint list (the number of these lists is variable, it is not a fixed number) and use the content of these lists to render n DropDown (the content of these drop down is the content of the related SharePoint list).
So basically into the Page_Load() method of my Web Part I have something like this (it works):
else if (mode != null && mode.Equals("scelta_campi_facoltativi_etichetta"))
{
SPList listaCampiOpzionaliEtichetta = contextWeb.Lists["ListaCampiOpzionaliEtichetta"];
String tipoDocumentiInternalName = listaCampiOpzionaliEtichetta.Fields["TipoDocumento"].InternalName;
Clausola c = null;
if (tipoDoc.Equals("docEntrata"))
{
c = new Clausola(Clausola.condizione.Eq, Clausola.tipoCampo.Choice, Clausola.CondizioneExtra.no, "Entrata", tipoDocumentiInternalName);
}
else if(tipoDoc.Equals("docUscita"))
{
c = new Clausola(Clausola.condizione.Eq, Clausola.tipoCampo.Choice, Clausola.CondizioneExtra.no, "Uscita", tipoDocumentiInternalName);
}
string q = Query.creaQueryWhere(c.query);
SPQuery queryQ = new SPQuery();
queryQ.Query = q;
SPListItemCollection etichetteCollection = listaCampiOpzionaliEtichetta.GetItems(queryQ);
Table table = new Table();
table.CellPadding = 2;
table.CellSpacing = 2;
table.Width = Unit.Percentage(100);
foreach (SPListItem item in etichetteCollection)
{
Debug.WriteLine("etichetta: " + item["NomeLista"] + " URL sito: " + item["UrlSito"]);
SPSite sitoEtichettaCorrente = new SPSite(item["UrlSito"].ToString()); // Top level website of the site collection
SPWeb currentWebSite = sitoEtichettaCorrente.OpenWeb();
//SPList eitchettaCorrenteList = currentWebSite.GetList(item["NomeLista"].ToString());
SPList eitchettaCorrenteList = currentWebSite.Lists[item["NomeLista"].ToString()];
String nomeColonna = item["NomeColonna"].ToString();
String codice = item["Codice"].ToString();
TableRow rigaCorrente = new TableRow();
TableCell cell1Corrente = new TableCell();
TableCell cell2Corrente = new TableCell();
cell1Corrente.Controls.Add(new LiteralControl((String)item["NomeLista"]));
DropDownList dropDownnEtichetta = new DropDownList();
for (int i = 0; i < eitchettaCorrenteList.Items.Count; i++)
{
dropDownnEtichetta.CssClass = "chosen-select";
dropDownnEtichetta.ClientIDMode = ClientIDMode.Static;
dropDownnEtichetta.ID = (String)item["NomeLista"];
string valoreDaMostrareInternalName = eitchettaCorrenteList.Fields[nomeColonna].InternalName;
string valoreDaStampareInternalName = eitchettaCorrenteList.Fields[codice].InternalName;
string valoreDaMostrare = eitchettaCorrenteList.Items[i].GetFormattedValue(valoreDaMostrareInternalName);
string valoreDaStampare = eitchettaCorrenteList.Items[i].GetFormattedValue(valoreDaStampareInternalName);
dropDownnEtichetta.Items.Add(new ListItem(valoreDaMostrare, valoreDaStampare));
cell2Corrente.Controls.Add(dropDownnEtichetta);
rigaCorrente.Controls.Add(cell1Corrente);
rigaCorrente.Controls.Add(cell2Corrente);
}
table.Controls.Add(rigaCorrente);
}
sceltaCampiEtichettaPanel.Controls.Add(table);
HtmlGenericControl buttondiv = new HtmlGenericControl("div");
Button bottoneConfermaCampiFacoltativiEtichetta = new Button();
bottoneConfermaCampiFacoltativiEtichetta.Text = "Conferma";
bottoneConfermaCampiFacoltativiEtichetta.CssClass = "shiny-blue";
//bottoneConfermaCampiFacoltativiEtichetta.OnClientClick = "return validatePwd();";
//bottoneConfermaCampiFacoltativiEtichetta.Click += ButtonSalva_Click;
buttondiv.Controls.Add(new LiteralControl("<br/>"));
buttondiv.Controls.Add(bottoneConfermaCampiFacoltativiEtichetta);
sceltaCampiEtichettaPanel.Controls.Add(buttondiv);
}
As you can see I am retrieving a list of SharePoint lists. I iterate on each list and I populate the contend of the rendered DropDown with the content of the related current list.
Now my problem is: the user can select a value from these DropDown. I want to store (probably at class level) the values chosen by the user into these dropdown.
What could be a smart strategy to implement this task?
The question may be a bit long :
I am making an Online Evaluation Portal and there different type of questions in database which needs to be loaded in the web- form. The questions can be Single Answer(radio button) or multi-answer(check box button). So depending upon the type I create the radio button or check box as per requirement and load it in the Repeater during Runtime. The code is as below :
SqlCommand cmd = new SqlCommand("select * from tbl_QuestionAnswer", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((string)dr["type"] == "SingleAnswer")
{
RadioButton rAnswer1 = new RadioButton();
rAnswer1.ID = "rbl_Answer1";
rAnswer1.GroupName = "QAnswer1";
rAnswer1.Text = dr["Answer1"].ToString();
Panel PAnswer1 = e.Item.FindControl("PAnswer1") as Panel;
PAnswer1.Controls.Add(rAnswer1);
RadioButton rAnswer2 = new RadioButton();
rAnswer2.ID = "rbl_Answer2";
rAnswer2.GroupName = "QAnswer1";
rAnswer2.Text = dr["Answer2"].ToString();
Panel PAnswer2 = e.Item.FindControl("PAnswer2") as Panel;
PAnswer2.Controls.Add(rAnswer2);
RadioButton rAnswer3 = new RadioButton();
rAnswer3.ID = "rbl_Answer3";
rAnswer3.GroupName = "QAnswer1";
rAnswer3.Text = dr["Answer3"].ToString();
Panel PAnswer3 = e.Item.FindControl("PAnswer3") as Panel;
PAnswer3.Controls.Add(rAnswer3);
RadioButton rAnswer4 = new RadioButton();
rAnswer4.ID = "rbl_Answer4";
rAnswer4.GroupName = "QAnswer1";
rAnswer4.Text = dr["Answer4"].ToString();
Panel PAnswer4 = e.Item.FindControl("PAnswer4") as Panel;
PAnswer4.Controls.Add(rAnswer4);
}
else
{
CheckBox cAnswer1 = new CheckBox();
cAnswer1.ID = "chk_Answer1";
cAnswer1.Text = dr["Answer1"].ToString();
Panel PAnswer1 = e.Item.FindControl("PAnswer1") as Panel;
PAnswer1.Controls.Add(cAnswer1);
CheckBox cAnswer2 = new CheckBox();
cAnswer2.ID = "chk_Answer2";
cAnswer2.Text = dr["Answer2"].ToString();
Panel PAnswer2 = e.Item.FindControl("PAnswer2") as Panel;
PAnswer2.Controls.Add(cAnswer2);
CheckBox cAnswer3 = new CheckBox();
cAnswer3.ID = "chk_Answer3";
cAnswer3.Text = dr["Answer3"].ToString();
Panel PAnswer3 = e.Item.FindControl("PAnswer3") as Panel;
PAnswer3.Controls.Add(cAnswer3);
CheckBox cAnswer4 = new CheckBox();
cAnswer4.ID = "chk_Answer4";
cAnswer4.Text = dr["Answer4"].ToString();
Panel PAnswer4 = e.Item.FindControl("PAnswer4") as Panel;
PAnswer4.Controls.Add(cAnswer4);
}
}
But the problem here is all the answers get loaded in all questions. i.e. from that dr["Answer1"] it takes all the data in the "Answer1" column and then makes a check-box or radio-button. I don't know why that is happening as it should take only onr row at a time and data from that row only.
Also this runs good till 2 questions. After that if I add 3rd question and try to load it, it gives error saying "Multiple controls with the same ID 'rbl_Answer1' were found. FindControl requires that controls have unique IDs.". And this is correct too. So I need a approach to load questions into the web-form dynamically depending on Single answer or multi -asnwer
It's very clear that you may create control with the same id if you have more than one row in your query.
Try to make dynamic field/control and set dynamic ID for those control
while (dr.Read())
{
if ((string)dr["type"] == "SingleAnswer")
{
RadioButton rAnswer1 = new RadioButton();
rAnswer1.ID = "rbl_Answer" + dr["AnswerID1"].ToString();
or something like that...
I know this is a well asked question and I found some marked as answers but those doesn't solve my problem. Please have a look at my codes..
Method to Display dynamic controls
private void ShowControlsByFormId()
{
List<FormControlsBO> list = new List<FormControlsBO>();
list = new FormControlsDA().FormControls_GetByFormId(Convert.ToInt32(ddlForm.SelectedValue.ToString()));
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
DynamicControl dynamicControl = CommonUtility.GenerateControl(list[i]);
pnlInput.Controls.Add(new LiteralControl("<tr><td>"));
pnlInput.Controls.Add(dynamicControl.GeneratedControlLiteral);
pnlInput.Controls.Add(new LiteralControl("</td><td></td><td>"));
pnlInput.Controls.Add(dynamicControl.GeneratedControl);
pnlInput.Controls.Add(new LiteralControl("</td><tr><br/><br/>"));
}
pnlAction.Visible = true;
}
else
{
pnlAction.Visible = false;
}
}
Method to Generate dynamic controls
public static DynamicControl GenerateControl(FormControlsBO bo)
{
DynamicControl dynamicControl = new DynamicControl();
Control control = new Control();
LiteralControl literal = new LiteralControl();
switch (bo.FieldType)
{
case "TextBox":
control = new TextBox();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "RadioButton":
control = new RadioButton();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "CheckBox":
control = new CheckBox();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "DropDownList":
control = new DropDownList();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
}
control.ClientIDMode = ClientIDMode.Static;
dynamicControl.GeneratedControl = control;
dynamicControl.GeneratedControlLiteral = literal;
return dynamicControl;
}
Method to Save data
private void FormRecords_Save()
{
List<FormControlsBO> list = new List<FormControlsBO>();
FormControlsBO bo = new FormControlsBO();
foreach (Control ctl in pnlInput.Controls)
{
CommonUtility.DataFiller(bo, ctl);
list.Add(bo);
}
Boolean result = false;
result = new FormControlsDA().FormRecords_Save(list);
if(result == true)
{
lblMessage.Text = "Form data saved successfully";
}
else
{
lblMessage.Text = "Form data not saved";
}
}
The problem is, when I debug the code, pnlInput.Controls shows Zero count. Please help !!
As I already answered here all dynamic controls should be reinitiated in Page's Init event, as viewstate manager values are set every request. You can check page's lifecycle.
So right now, when you do not create you control in init event, viewstates misses them while it is setting postback data, and when you do try to get values, they are equal to zeros.
Keep in mind, that you have to create the same control types with the same names.
If you have written the code to generate Dynamic Controls and if it is in the page load event use FindControl("IdofControl"); to retrive its value;
For Example,
TextBox txtInstance = (TextBox)FindControl("IdofControl");
string txtvalueinTextBox =txtInstance.Text;
Make sure that the controls are dynamically generated in all page reloads.If the controls generated on the postback is different the viewState may not restore back properly.
I am working on exporting data and right now some fields export the value, instead of the text. So I am saving the object that returns the text and value to a list box and matching it to the value in the listbox from the object like so:
MaterialDB materials = new MaterialDB();
DropDownList listBoxMaterials = new DropDownList();
listBoxMaterials.DataSource = materials.GetItems(ModuleId, TabId);
listBoxMaterials.DataBind();
string materialString = "";
foreach (ListItem i in listBoxMaterials.Items)
{
if (i.Value == row["MaterialTypeID"].ToString())
{
materialString = i.Text;
}
}
When I use this for the i.Value it always returns "System.Data.DataRowView" instead of the actual value. I'm doing this all in code behind. Anyway around this to get it to work?
Thanks!
You need to set the DataTextField and DataValueField properties of the DropDownList. Example:
MaterialDB materials = new MaterialDB();
DropDownList listBoxMaterials = new DropDownList();
listBoxMaterials.DataSource = materials.GetItems(ModuleId, TabId);
listBoxMaterials.DataTextField = "MaterialName";
listBoxMaterials.DataTextValue = "MaterialID";
listBoxMaterials.DataBind();
string materialString = "";
foreach (ListItem i in listBoxMaterials.Items)
{
if (i.Value == row["MaterialTypeID"].ToString())
{
materialString = i.Text;
}
}
I have a HtmlGenericController and to this I want to add RadioButtons. My radiobuttons come from a RadioButtonList an hence the objects are Listitems. How do I get my genericcontroller to show the radiobuttons?
This is my code
private HtmlGenericControl generateCells(String domainName)
{
HtmlGenericControl container = new HtmlGenericControl("div");
HtmlGenericControl dName = new HtmlGenericControl("span");
dName.InnerHtml = domainName;
RadioButtonList radioList = new RadioButtonList();
radioList.ID = "radio_" + domainName;
radioList.RepeatDirection = RepeatDirection.Horizontal;
ListItem sunriseA = new ListItem();
sunriseA.Value = Price_Types.SUNRISE_ONE.ToString();
//sunriseA.Text = Price_Types.SUNRISE_ONE.ToString();
sunriseA.Text = "";
radioList.Items.Add(sunriseA);
ListItem sunriseB = new ListItem();
sunriseB.Value = Price_Types.SUNRISE_TWO.ToString();
//sunriseB.Text = Price_Types.SUNRISE_TWO.ToString();
sunriseB.Text = "";
radioList.Items.Add(sunriseB);
ListItem landrush = new ListItem();
landrush.Value = Price_Types.LANDRUSH.ToString();
//landrush.Text = Price_Types.LANDRUSH.ToString();
landrush.Text = "";
radioList.Items.Add(landrush);
ListItem general = new ListItem();
general.Value = Price_Types.GENERAL.ToString();
//general.Text = Price_Types.GENERAL.ToString();
general.Text = "";
radioList.Items.Add(general);
container.Controls.Add(dName);
foreach (ListItem item in radioList.Items)
{
HtmlGenericControl span = new HtmlGenericControl("span");
span.InnerHtml = item;//what to put here??
container.Controls.Add(span);
}
return container;
}
var radioButton = new HtmlGenericControl("input");
radioButton.Attributes["type"] = "radio";
radioButton.Attributes["name"] = "groupName";
radioButton.Attributes["value"] = "buttonValue";
That will only render the round radiobutton itself, though. To add a label, you'll have to render for example a span besides it. Or, IIRC, render a label field with the for attribute set to the ID of the radiobutton, so clicking the label will automatically click the button too.