Dynamically add checkboxlist into placeholder and get the checked value of the checkboxlist - asp.net

I am creating an admin Page, in which checkboxlist(User list from DB)is to be created dynamically and its the checked users value is retrieved.
There are different types of users, so it is distinguised groupwise.
Now first a panel is defined, the checkboxlist is created dynamically and placed inside the panel, then the panel is placed inside a Placeholder.
What Iam doing here is placing the checkboxlist inside the panel, then the panel inside the placeholder. So the values of the Checkboxlist is not retrieved, due to the panel it doesnt get the checkboxlist and it doesn't loop through the Checkboxlist.
What I have done is.
private void AddControl(string pUserGrp, int pUserGrp_Id, int pName)
{
CheckBoxList chkList = new CheckBoxList();
CheckBox chk = new CheckBox();
User us = new User();
us.OrderBy = "Order By User_Name";
us.WhereClause = "Where UserRole_Id = " + pUserGrp_Id ;
chkList.ID = "ChkUser" + pName ;
chkList.AutoPostBack = true;
chkList.Attributes.Add("onClick", "getVal(ChkUser" + pName + ");");
chkList.RepeatColumns = 6;
chkList.DataSource = us.GetUserDS();
chkList.DataTextField = "User_Name";
chkList.DataValueField = "User_Id";
chkList.DataBind();
chkList.Attributes.Add("onClick", "getVal(this);");
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);
Place.Controls.Add(pUser);
}
private void setChecked(int pPageGroupId)
{
ArrayList arr = new ArrayList();
PageMaster obj = new PageMaster();
obj.WhereClause = " Where PageGroup_Id = " + pPageGroupId;
arr = obj.GetPageGroupUserRights(null);
CheckBoxList chkList = (CheckBoxList)Place.FindControl("ChkUser");
if (chkList != null)
{
for (int i = 0; i < chkList.Items.Count; i++)
{
if (arr.Count > 0)
{
int ii = 0;
while (ii < arr.Count)
{
PageMaster oCand = (PageMaster)arr[ii];
if (oCand.User_Name == chkList.Items[i].Text)
{
if (!chkList.Items[i].Selected)
{
chkList.Items[i].Selected = true;
}
}
ii++;
oCand = null;
}
}
}
}
}
public string GetListCheckBoxText()
{
StringBuilder sbtext = new StringBuilder();
foreach (Control c in Place.Controls)
{
if (c.GetType().Name == "CheckBoxList")
{
CheckBoxList cbx1 = (CheckBoxList)c;
foreach (ListItem li in cbx1.Items)
{
if (li.Selected == true)
{
sbtext.Append(",");
sbtext.Append(li.Value);
}
else
{
sbtext.Append(li.Value);
}
}
}
}
return sbtext.ToString(); }
It doesnt get through the Checkboxlist control in the setChecked(), also doesnt loop through the GetListCheckBoxTest().
Anyone can plz help me.
Regards

The problem is that you are trying to find a control (in setChecked) without setting the Name property. You are using this:
CheckBoxList chkList = (CheckBoxList)Place.FindControl("ChkUser");
But where is this in AddControl?
chkList.Name = "ChkUser";
And in GetListCheckBoxText instead of...
if (c.GetType().Name == "CheckBoxList")
...use this:
if (c.GetType()== typeof(CheckBoxList))

Related

how to get value from dynamically created textbox in asp.net

hi i'm Cannot get value dynamically created textbox and save into database. plz help
his is code which I have created in this code text box are created but when I will input the value in the text and retrieve the value from dynamically created text box it give error
protected void btnAtt_Click(object sender, EventArgs e)
{
int DPLID = int.Parse(DPLCategory.Text);
var query = (from p in database.tbl_Attributes
where p.ProductTypeId_FK == DPLID
select new
{
p.Attribute_Id,
p.AttributeName,
p.ProductTypeId_FK,
}).ToArray();
for (int i = 0; i < query.Count(); i++)
{
Label lblatt = new Label();
lblatt.ID = query[i].AttributeName;
lblatt.Text = query[i].AttributeName + " : ";
lblatt.CssClass = "control-label";
TextBox txtatt = new TextBox();
txtatt.ID = "txtatt"+i;
txtatt.Attributes.Add("runat", "server");
txtatt.Text = String.Empty;
txtatt.CssClass = "form-control input-sm";
HtmlTextWriterTag.Br.ToString();
Place1.Controls.Add(lblatt);
HtmlTextWriterTag.Br.ToString();
Place1.Controls.Add(txtatt);
HtmlTextWriterTag.Br.ToString();
}
}
protected void lbtnSave_Click(object sender, EventArgs e)
{
int DPLID = int.Parse(DPLCategory.Text);
var query = (from p in database.tbl_Attributes
where p.ProductTypeId_FK == DPLID
select new
{
p.Attribute_Id,
p.AttributeName,
p.ProductTypeId_FK,
}).ToArray();
int LastId = database.tbl_Products.Max(p => p.ProductId);
for (int i = 0; i < query.Count(); i++)
{
database.tbl_ProductValue.Add(new Models.tbl_ProductValue()
{
ProductId_FK = LastId,
AttributeID_FK = query[i].Attribute_Id,
ProductValue = ??,
});
database.SaveChanges();
}
}
plz help me for how to get textbox?
I haven't worked with WebForms in a while but you can access the controls by their IDs like this:
ProductValue = ((TextBox)FindControl("txtatt" + i)).Text;

FormView IBindableTemplate can't get new values out of FormViewUpdateEventArgs e

I have dynamic forms that are build from xml. I can generate the form but I can't get new values from it. I get only the old values that were generated. I would like to update values that are diffrent from old. I think the problem is that I override the new values on page_init with old ones?
This is a dropbox link to my UI for better understanding what I want to achive : https://www.dropbox.com/s/nacs9ohgjxefft9/FormView.png?dl=0#
public sealed class FormViewEditTemplate : IBindableTemplate
{
public FormViewEditTemplate(ListItemType type, mmXMLdoc.mmXMLdoc editXmlForm)
{
templateType = type;
_editXmlForm = editXmlForm;
}
//This method provides a way to insert an instance of text and controls into the specified container.
void ITemplate.InstantiateIn(Control container)
{
tabela = new Table();
tabs = new TabContainer();
tapPanel = new TabPanel();
row = new TableRow();
switch (templateType)
{
case ListItemType.EditItem:
List<XmlElement> Controls = _editXmlForm.getNodCollection("//Tabs");
if (Controls.Count > 0)
{
//pridobimo tabe za formo
foreach (XmlElement ctrlItem in Controls)
{
var ControlsItems = _editXmlForm.getNodCollection("./Controls", "Control", -1, ctrlItem);
tabela = new Table();
tapPanel = new TabPanel();
tapPanel.ID = Guid.NewGuid().ToString();
tapPanel.HeaderText = ctrlItem.GetAttribute("name").ToString();
//pridobimo podatke za formo
//var controls1 = ctrlItem.SelectNodes("//Controls");
foreach (XmlElement ctrl in ControlsItems)
{
string name = _editXmlForm.gStr("./#name", -1, ctrl) + Guid.NewGuid().ToString();
string label = _editXmlForm.gStr("./#label", -1, ctrl);
string width = _editXmlForm.gStr("./#width", -1, ctrl);
string type = _editXmlForm.gStr("./#type", -1, ctrl);
string value = String.Empty;
string helpnote = _editXmlForm.gStr("./HelpNote", -1, ctrl);
string boundfield = _editXmlForm.gStr("./BoundField", -1, ctrl);
row = new TableRow();
TableCell cell = new TableCell();
switch (type)
{
case "TextBox":
//The TemplateField allows for a mix of HTML markup, Web controls, and data-binding syntax.
Label lbl_item = new Label();
lbl_item.Font.Bold = true;
lbl_item.Text = label + ": ";
cell = new TableCell();
cell.Controls.Add(lbl_item);
row.Controls.Add(cell);
TextBox txt_item = new TextBox();
txt_item.ID = boundfield;
txt_item.Text = boundfield;
txt_item.DataBinding += new EventHandler(txt_DataBind);
cell = new TableCell();
cell.Controls.Add(txt_item);
row.Controls.Add(cell);
break;
case "CheckBox":
lbl_item = new Label();
lbl_item.Font.Bold = true;
lbl_item.Text = label + "<br/>";
//The BoundField displays the value of specified DataSource field as text.
BoundField bfield = new BoundField();
bfield.HeaderText = label;
bfield.DataField = boundfield;
break;
default:
break;
}
tabela.Controls.Add(row);
}
tapPanel.Controls.Add(tabela);
tabs.Controls.Add(tapPanel);
}
}
break;
case ListItemType.Footer:
Button saveButton = new Button();
saveButton.Command += new CommandEventHandler(SaveButton_Command);
saveButton.CommandName = "Update";
saveButton.Text = "Save";
saveButton.ID = "EditButton";
container.Controls.Add(saveButton);
break;
}
container.Controls.Add(tabs);
}
IOrderedDictionary IBindableTemplate.ExtractValues(Control container)
{
OrderedDictionary dict = new OrderedDictionary();
List<XmlElement> Controls = _editXmlForm.getNodCollection("//Tabs");
if (Controls.Count > 0)
{
//pridobimo tabe za formo
foreach (XmlElement ctrlItem in Controls)
{
var ControlsItems = _editXmlForm.getNodCollection("./Controls", "Control", -1, ctrlItem);
foreach (XmlElement ctrl in ControlsItems)
{
string type = _editXmlForm.gStr("./#type", -1, ctrl);
string boundfield = _editXmlForm.gStr("./BoundField", -1, ctrl);
switch (type)
{
case "TextBox":
TextBox tb = (TextBox)FindControlRecursive(container, boundfield);
if (tb != null)
dict[boundfield] = tb.Text;
break;
case "Label":
Label lb = (Label)FindControlRecursive(container, boundfield);
if (lb != null)
dict[boundfield] = lb.Text;
break;
case "CheckBox":
CheckBox cb = (CheckBox)FindControlRecursive(container, boundfield);
if (cb != null)
dict[boundfield] = cb.Checked;
break;
case "DropDown":
DropDownList ddl = (DropDownList)FindControlRecursive(container, boundfield);
if (ddl != null)
dict[boundfield] = ddl.SelectedValue;
break;
default:
break;
}
}
}
}
return dict;
}
private Control FindControlRecursive(Control ctlRoot, string sControlId)
{
// if this control is the one we are looking for, break from the recursion
// and return the control.
if (ctlRoot.ID == sControlId)
{
return ctlRoot;
}
// loop the child controls of this parent control and call recursively.
foreach (Control ctl in ctlRoot.Controls)
{
Control ctlFound = FindControlRecursive(ctl, sControlId);
// if we found the control, return it.
if (ctlFound != null)
{
return ctlFound;
}
}
// we never found the control so just return null.
return null;
}
I call this in Page_init
protected void Page_Init(object sender, EventArgs e)
{
FormViewEdit.HeaderTemplate = new FormViewEditTemplate(ListItemType.Header, editXmlForm);
FormViewEdit.EditItemTemplate = new FormViewEditTemplate(ListItemType.EditItem, editXmlForm);
FormViewEdit.FooterTemplate = new FormViewEditTemplate(ListItemType.Footer, editXmlForm);
FormViewEdit.ItemUpdating += new FormViewUpdateEventHandler(FormView1_ItemUpdating);
EditFormView.SelectCommand = "SELECT * FROM " + UniqueTable + " WHERE " + PrimaryKey + "=" + ident;
EditFormView.DataBind();
}
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
//TODO get all new values and make query string.
EditFormView.UpdateCommand = "UPDATE " + UniqueTable + " SET bla_Opis='" + e.NewValues["bla_Opis"] + "' WHERE " + PrimaryKey + "=" + ident;
EditFormView.Update();
EditFormView.DataBind();
}
I found the problem. I used randomly generated id for tap panel therfore I believe the the two way binding didnt work on post back. On every postback I got new id and the old data didnt find control to bind the new values.
tapPanel.ID = Guid.NewGuid().ToString();

ASP .NET Wizard Control and View State

I have a form with 3 wizard steps, and when i click the button to dynamically add text boxes, that works fine, but when i go to the next step and i click on add to add more text boxes, it automatically adds all the text boxes from the previous steps and then continues to add if i keep click on it.
How do i prevent that from happening.
private List ControlsList
{
get
{
if (ViewState["controls"] == null)
{
ViewState["controls"] = new List();
}
return (List)ViewState["controls"];
}
}
private int NextID
{
get
{
return ControlsList.Count + 1;
}
}
protected override void LoadViewState(object savedState)
{
string section = Wizard1.ActiveStep.ID;
int sectionNum = Wizard1.ActiveStepIndex;
var control = Wizard1.ActiveStep.FindControl("Place" + sectionNum) as PlaceHolder;
base.LoadViewState(savedState);
int count = 0;
foreach (string txtID in ControlsList)
{
if (count == 0)
{
control.Controls.Add(new LiteralControl("<tr>"));
}
TextBox txt = new TextBox();
control.Controls.Add(new LiteralControl("<td>"));
txt.ID = txtID;
control.Controls.Add(txt);
control.Controls.Add(new LiteralControl("</td>"));
count = count + 1;
if (count == 3)
{
control.Controls.Add(new LiteralControl("</tr>"));
count = 0;
}
}
}
protected void AddControlButton_Click(object sender, EventArgs e)
{
string section = Wizard1.ActiveStep.ID;
int sectionNum = Wizard1.ActiveStepIndex;
var control = Wizard1.ActiveStep.FindControl("Place" + sectionNum) as PlaceHolder;
TextBox txt1 = new TextBox();
TextBox txt2 = new TextBox();
TextBox txt3 = new TextBox();
txt1.ID = section.ToString() + "Size" + NextID.ToString();
control.Controls.Add(new LiteralControl("<td>"));
control.Controls.Add(txt1);
control.Controls.Add(new LiteralControl("</td>"));
ControlsList.Add(txt1.ID);
txt2.ID = section.ToString() + "Description" + NextID.ToString();
control.Controls.Add(new LiteralControl("<td>"));
control.Controls.Add(txt2);
control.Controls.Add(new LiteralControl("</td>"));
ControlsList.Add(txt2.ID);
txt3.ID = section.ToString() + "Quantity" + NextID.ToString();
control.Controls.Add(new LiteralControl("<td>"));
control.Controls.Add(txt3);
control.Controls.Add(new LiteralControl("</td></tr>"));
ControlsList.Add(txt3.ID);
}
You are storing all of the dynamic textboxes in ViewState and then the ControlsList property getter is returning the whole list when it is building the textboxes.
My recommendation is to use Session cache instead of ViewState, because it will allow you to differentiate the textbox controls from each of the wizard steps, like this:
Session["WizardStep1"] = listOfTextBoxesFromStep1;
Session["WizardStep2"] = listOfTextBoxesFromStep2;
Session["WizardStep3"] = listOfTextBoxesFromStep3;

how to check items in checkboxlist?

i have a checkboxlist that i want to check some of it's items,
items that i wanna check store in database, i'm selecting them from database and in a loop i wrote thees but just last item selected :(( :
var selectedRoles = (from r in DataContext.Context.Core_PagesPermission
where r.PageName.Contains(pageName) select r)
.FirstOrDefault();
if(selectedRoles != null)
{
string roles = selectedRoles.Roles;
string[] role = roles.Split(',');
int countTags = role.Count();
foreach (string word in role)
{
CheckBoxList1.SelectedValue = word;
Response.Write(word + "<br/>");
countTags -= 1;
}
}
this worked :
var selectedRoles = (from r in DataContext.Context.Core_PagesPermission where r.PageName.Contains(pageName) select r)
.FirstOrDefault();
dsRoles.DataBind();
CheckBoxList1.DataBind();
if(selectedRoles != null)
{
string roles = selectedRoles.Roles;
string[] role = roles.Split(',');
foreach (string word in role)
{
try
{
CheckBoxList1.Items.FindByValue(word).Selected = true;
}
catch (Exception exp)
{
lbError.Text= exp.ToString();
}
You will want to select the individual items:
CheckBoxList1.Items.FindByText(word).Selected = true;
or
CheckBoxList1.Items.FindByValue(word).Selected = true;
However, if the checkboxlist doesn't have the text/value you are looking for, it will throw an error.
datatable method checkboxlist
for (int i = 0; i < dt.Rows.Count; i++)
{
chkCategories.Items.FindByValue(dt.Rows[i]["CategoryID"].ToString()).Selected = true;
}

Selected Index changed doesnt fire

I have a drop down list that is populated on page load and by default the selected index is 0 and its set to an emty string. On page load if we change the selected value the selected index method doesnt fire.
if(!page.isPostback)
{
this.ddl.DataSource = list;
this.ddl.DataValueField = "Id";
this.ddl.DataTextField = "Name";
this.ddl.DataBind();
this.ddl.Items.Insert(0, String.Empty);
if (Request.QueryString != null)
{
string name = Request.QueryString["name"];
long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault();
this.selectedIndex = 1;
this.ddl.SelectedValue = Id.ToString();
}
}
That's as it should be. If you want to execute some piece of logic from both the event and/or from page load, put that logic in a separate method so you can call it easily from your page load.
private void BindList()
{
this.ddl.Items.Clear();
this.ddl.DataSource = list;
this.ddl.DataValueField = "Id";
this.ddl.DataTextField = "Name";
this.ddl.DataBind();
this.ddl.Items.Insert(0, String.Empty);
this.ddl.Items.SelectedIndex = 0;
}
if(!page.isPostback)
{
BindList();
if (Request.QueryString != null)
{
string name = Request.QueryString["name"];
long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault();
this.ddl.Items.ClearSelection();
this.ddl.Items.FindByValue(Id.ToString()).Selected = true;
}
}

Resources