ASPx controls not present in PostBack when created in code behind - c#

I created a LayoutGroup in this way:
protected void Page_LoadComplete(object sender, EventArgs e){
LayoutGroup layoutGroup = new LayoutGroup
{
Caption = "Services",
Name = "Services",
ColumnCount = 4
};
foreach (Service service in services)
{
LayoutItem layoutItem = new LayoutItem
{
Caption = service.Name
};
ASPxCheckBox checkBox = new ASPxCheckBox
{
Value = service.ID,
};
layoutItem.Controls.Add(checkBox);
layoutGroup.Items.Add(layoutItem);
}
MyFormLayout.Items.Add(layoutGroup);
}
I had to write this code in Page_LoadComplete and not in Page_Init because this code should be executed after an event is raised (getting the "services" list after an item in a combobox is selected).
I also have a submit button, and I want to retrieve the CheckBoxs' values from its event, like this :
protected void SubmitButton_Click(object sender, EventArgs e)
{
LayoutGroup layoutGroupServices = MyFormLayout.FindItemOrGroupByName("Services") as LayoutGroup;
foreach (LayoutItem item in layoutGroupServices.Items)
{
var debug = item.Controls;
}
}
but Controls is an empty list. How can I retrieve the checkboxes? Thank you in advance

Related

button click event to create new asp.net combobox

I have an existing drop down list(namely ddlA). On selecting a value in which, I am getting a cascading drop down list(ddlB). The requirement is, I need to create a button on the webform. By clicking the button, I would need to create drop down list dynamically of type ddlA. But here is the tricky part, I am required to present all the values in this dropdown except the selected value in the previous selection(s) of type ddlA.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<DropDownList> DDLList = new List<DropDownList>();
Session["DDLs"] = DDLList;
}
else
{
List<DropDownList> existingDropDowns = (List<DropDownList>)Session["DDLs"];
//Add all existing DropDownLists to Panel
foreach (DropDownList dropdown in existingDropDowns)
{
Panel1.Controls.Add(dropdown);
dropdown.AutoPostBack = true;
Panel1.Controls.Add(new LiteralControl("<br/>"));
}
Session["DDLs"] = existingDropDowns;
}
}
and here is my button click event code:
protected void ddlAdditionBtn_Click(object sender, EventArgs e)
{
List<DropDownList> existingDropDowns = (List<DropDownList>)Session["DDLs"];
DropDownList newDropDown = new DropDownList();
newDropDown.ID = "DDL" + existingDropDowns.Count.ToString();
existingDropDowns.Add(newDropDown);
Panel1.Controls.Add(newDropDown);
newDropDown.AutoPostBack = true;
Panel1.Controls.Add(new LiteralControl("<br/>"));
Session["DDLs"] = existingDropDowns;
}
Below is the code to connect the existing dropdown list with the database.
protected void GetDropDowndata()
{
DataTable ddlData= lookupCache.AccessLookupData(Constants.GroupSelectionFilter.ToString());
if (ddlData != null && ddlData.Rows.Count > 0)
{
ddlData.DefaultView.Sort = "DropDownValue";
ddlData = groupsData.DefaultView.ToTable();
ddlSelectGrp.DataSource = ddlData;
ddlSelectGrp.DataTextField = "DropDownValue";//ddlSelectGrp is the existing dropdown id
ddlSelectGrp.DataValueField = "DropDownBoxID";
ddlSelectGrp.DataMember = "DropDownGroup";
ddlSelectGrp.DataBind();
ddlSelectGrp.Items.Insert(1, Constants.GroupAll.ToString());
ddlSelectGrp.SelectedIndex = 1;
btnGroupSave.Enabled = true;
btnGroupSave.CssClass = "saveButton";
}
}
But I have no idea on how to connect the dynamically generated dropdownlist with the datasource and that too without the selected value(s) in the previous dropdown list(s).

Binding dynamic datalist in C#

I am trying to create a dynamic Data List bind with database. I can easily create this but I am not able to make the item Command of this Data List. Please help me. Here is my code below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
categorybinding();
}
}
public void categorybinding()
{
int totalcate = (from x in ebooks.books_category select x).Count();
var ra = (from x in ebooks.books_category select x);
DataList dl = new DataList();
dl.ItemTemplate = new DatalistLabelColumnBind();
dl.DataSource = ra;
dl.DataBind();
form1.Controls.Add(dl);
dl.ItemCommand += new DataListCommandEventHandler(this.ItemCommandHandler);
}
public void ItemCommandHandler(object sender, DataListCommandEventArgs e)
{
Response.Redirect("NewPage.aspx?"+e.CommandArgument.ToString());
}
//Create a new class implementing ITemplate
public class DatalistLabelColumnBind : ITemplate
{
public DatalistLabelColumnBind()
{
//Add constructor
}
public void InstantiateIn(Control container)
{
LinkButton label1 = new LinkButton();
label1.DataBinding += new EventHandler(this.BindLabelColumn);
container.Controls.Add(label1);
}
public void BindLabelColumn(object sender, EventArgs e)
{
LinkButton lbl = (LinkButton)sender;
DataListItem container = (DataListItem)lbl.NamingContainer ;
String strVals = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "books_category1"));
lbl.CommandArgument = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "id_books"));
lbl.Text = strVals;
}
}
My Problem :
My Data List easily added on the page but when I click on the Link Button which is added in the Data List is does not Redirect to the NewPage.aspx
Help me out..
I think your Response.Redirect is not resolving to the intended page.
Try:
Response.Redirect("~/NewPage.aspx?"+e.CommandArgument.ToString());
Write categorybinding() function after the if condition in Page_Load. And ItemCommandHandler will definitely work.

c# add button event programmatically

Trying to add buttons programmatically to a webform.
Some work - others don't.
In the code below I add btnY and btnX in the Page_Load.
These both work - they show on the page and fire the event
and the code in the event handler works....
In the page load I also run bindData which gets a DataTable
and uses the data to create controls.
in the example I am only creating Button.
These buttons will appear on the page correctly but when clicked
they only do a postback ..
the code in the event handler doesn't work - does it get called?
The event handler is the same for all the buttons.
Any ideas why or how I can make it work?
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(btn("btnY", "Y"));
Pages P = new Pages();
bindData(P.DT);
PlaceHolder1.Controls.Add(btn("btnX", "X"));
}
Button btn(string id, string text)
{
Button btn1 = new Button();
btn1.ID = id;
btn1.Text = text;
btn1.Click += new System.EventHandler(this.btn_click);
return btn1;
}
protected void bindData(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
render(Convert.ToInt32(row["PageKey"]));
}
}
protected void render(int pageKey)
{
PlaceHolder1.Controls.Add(btn("btn_" + pageKey.ToString(), "Edit"));
}
protected void btn_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string id = btn.ID;
Pages P = new Pages();
bindData(P.DT);
lt.Text = "ID=" + id;
}
Never mind .. figured it out .. example above should work, my actual code had a if (!Page.PostBack) that caused the problem

Checkbox added programmatically not found

I add checkboxes that way:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CheckBox FieldCh = new CheckBox();
FieldCh.ID = "Field_" + Field.Id;
Panel1.Controls.Add(FieldCh);
}
}
but when I try to get this checkboxes from form:
foreach (Control item in FindControl("FieldForm").Controls)
{
if (item is Panel)
{
foreach (Control checkbox in item.Controls)
i cannot find this checkboxes :/ This could be problem with runat=server? I not find this property in Checkbox ..
If you want to find this CheckBox after PostBack (what I've assumed), you need to recreate it. Try to create this CheckBox out of if(!PostBack) clause (so it's recreated after postback too):
protected void Page_Load(object sender, EventArgs e)
{
CheckBox FieldCh = new CheckBox();
FieldCh.ID = "Field_" + Field.Id;
Panel1.Controls.Add(FieldCh);
if (!IsPostBack)
{
// ....
}
}
You must have to use Page_Load even to add controls dynamically.
protected void page_load()
{
CheckBox FieldCh = new CheckBox();
FieldCh.ID = "Field_" + Field.Id;
Panel1.Controls.Add(FieldCh);
}
you may simply use a better method of finding your control
just use this
CheckBox chkBox = this.form1.FindControl("YourControlId") as CheckBox;

ASPX post back problems with combobox

I've created a simple ASPX page that lists records in a GridView. The records are a list of incidents and one of the columns is the ID of the person who reported the incident.
The initial page shows all records but I would like to provide a filter for the ReportedBy column. I've gotten this working by allowing the user to type in the ReportedByID in a textbox and then clicking on the submit button. This refreshes the page as expected with the filtered view.
The code for this page is as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;
if (int.TryParse(txtReportedById.Text, out reportedById) == false)
{
reportedById = 0;
}
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}
To make it more user friendly, I decided to add a dropdown box populated with the ReportedBy names for the user to select which would then be used to filter on upon clicking the submit button. The dropdown box has names as the display items but the values should still be set to the IDs.
The problem I have is that the ID number I get from the dropdown box always comes up as the first element of the list rather than the one the user selected at the time they clicked on the submit button.
The code for this page with this implementation is as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
DataAccessObj daObj = new DataAccessObj();
foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}
if (IsPostBack == false)
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;
if (combobox.SelectedItem != null)
{
if (int.TryParse(combobox.SelectedItem.Value, out reportedById) == false)
{
reportedById = 0;
}
}
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}
Any help would be gratefully appreciated. TIA
Keep in mind that with WebForms the Page_Load code is executed before the event handler code for the control which created the postback.
You have to populate the list in the section where postbacks flags are checked, just like you do with the grid.
if (IsPostBack == false){
//bind the combobox
}
Otherwise, on a postback, the list will re-populate and the selection will be gone.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataAccessObj daObj = new DataAccessObj();
foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}

Categories

Resources