Asp Checkboxlist Loses Values After PostBack - asp.net

I have a checkboxlist control that I need to check the values of when a Submit button is clicked by the user onscreen(C#).
This checkboxlist is part of a user control that I am referencing within my page markup.
However, when I check the values of the checkboxlist within the code of the submit button, all of the values are gone (i.e it says there are no items at all in the checkboxlist control).
Anyone know why this would be happening? I am doing the exact same thing in code in another place with another checkboxlist user control and it works perfectly.
I don't have my exact code to hand but below is a simplified version of what I am doing.
Basically I am binding data to the Checkboxlist only when it is NOT a postback on the usedr control.
USER CONTROL WHICH CONTAINS ONLY THE CHECKBOXLIST CONTROL Page_Load()
If(!IsPostBack)
{
foreach(var item in myVals)
{
ListItem i = new ListItem();
i.Text = item.Text;
i.Value = item.Value;
i.Selected = false;
myCheckBoxListControl.Add(i);
}
}
Now I have a submit button function which checks the values in the checkboxlist...
SubmitButton_Click()
{
foreach(ListItem item in myCheckBoxListControl.Items)
{
// process each one here. The code never gets in here as there are never any items in the checkboxlist
}
}
Anyone know why the CheckboxList has lost all of its items by the time the submit button function gets executed? The checkboxlist has EnableViewState set to true.

Related

Best way to allow postback on a gridview without viewstate

My gridview is basically a hit list of results from which the user selects one, and I want to get a postback saying which one he has selected. There is no need for the grid contents to survive the postback round-trip because the hit list disappears as soon as he has selected an item.
I don't want to use viewstate because the hit list is likely to be large. I don't want to databind from the database in PageLoad to repopulate the grid because the search may take a while.
what I'm thinking at the moment is that I can put some javascript on the 'select' link to store the ID of the selected item in a hidden field and then call __doPostBack
this still seems a bit clunky. can you think of a cleaner way?
If the postback should be triggered when the user clicks the anywhere in the row, use the ItemDataBound event to attach a client onclick handler:
protected void GridView1_ItemDataBound(object sender, GridViewRowEventArgs e)
{
var dataItem = e.Item as GridViewRow;
if (dataItem != null)
{
dataItem.Attributes["onclick"] = string.Format("__doPostBack(this, '{0}')", e.Row.RowIndex);
}
}
Is the ID of the selected item something sensitive that should not be seen by the user?
If it is not, you could just make your select button a link to the next page, with the ID as a querystring variable. Clicking would just move to the next page, no postback required.

asp:DataPager onclick event

I am working with the .Net List view along with a data pager to enable pagination for a list view.
I am able to set the pagination working perfectly for the list view but I wish to have a method being called when ever the user clicks on any of the page numbers in the data pager.
I want to perform some operation whenever the page number is called. I guess there is no onclick event, so is there any other way by which this is possible.
Thanks
you can set it as imagebutton or linkbutton.
I have piece of code.. you just need to implement it.
you can set link and click event.
foreach (DataPagerFieldItem dpfItem in dtpPaging.Controls)
{
foreach (Control cPagerControls in dpfItem.Controls)
{
if (cPagerControls is ImageButton)
{
ImageButton imgNavigation = cPagerControls as ImageButton;
imgNavigation.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl);
imgNavigation.Click += new ImageClickEventHandler(imgNavigation_Click);
}
if (cPagerControls is LinkButton)
{
LinkButton lnkNumbers = cPagerControls as LinkButton;
lnkNumbers.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl);
lnkNumbers.Click += new EventHandler(lnkNumbers_Click);
}
}
}
You can bind a handler to the OnPagePropertiesChanging Event of the List View. A PagePropertiesChangingEventArgs object is passed to the handler as argument which contains MaximumRows and StartRowIndex properties. You can use these to calculate the current page number. It is very easy and requires no code-behind event binding as the solution proposed by sikender.

Get Value From Dynamic Control in Page Asp.Net

I have a dynamically created bill of material with each line item being a dynamic user_control. the user_control has a textbox for quantity entry. When I click the submit button i'd like to get all the quantities from each textbox but the controls have all disappeard on the page load and the page shows zero controls.
I know you can turn on autopostback for the textbox then catch each individual text_changed_event but that doesn't seem efficient. I'd like to just loop through all of them when user clicks submit button, then take them back to the same bill of material page.
First of all the reason why controls disappear on postback is that they were added to your page dynamically and when postback occurred the information about the dynamic controls were lost and page had no information about these dynamic controls.
Now about getting the values from controls inside dynamic user controls, you have use the FindControl method or have to iterate through the Controls collection of user control to get the reference to TextBoxes.
An idea about how to do this:
//1. Using ID of user control
//inside button_click method
protected void btnSubmit_Click(...)
{
TextBox txt1 = idOfUserControl.FindControl(textBoxId);
}
//2. Using type of user control
//inside button_click method
protected void btnSubmit_Click(...)
{
foreach(Control c in Page.Controls)
if(c is YourUserControlClass)
{
YourUserControlClass control = (YourUserControlClass)c;
TextBox txt1 = c.FindControl(textBoxId);
}
}

ASP.NET DropDownList not retaining selected item on postback

I have an ASP DropDownList that gets populated on the Page_Load event, after i select an item and hit a button the selected item gets cleared and the first item in the DropDownList gets selected. (The DropDownList is only populated when the page is not postback)
if (!IsPostBack)
{
List<Country> lCountries = new List<Country>();
List<CompanySchedule> lCompanySchedules = new List<CompanySchedule>();
this.Load_Countries(lCountries);
this.Load_Schedules(lCompanySchedules);
if (personnelRec == null)
{
personnelRec = new Personnel();
}
if (Request.QueryString["UA"] != null && Convert.ToInt32(Request.QueryString["UA"].ToString()) > 0)
{
userAccount.ID = Convert.ToInt32(Request.QueryString["UA"].ToString());
App_Database.Snapshift_Select_Helper.SNAPSHIFT_SELECT_PERSONNEL_APP_ACCOUNT(ref userAccount);
}
this.imgEmployeePicture.ImageUrl = "./images/Employees/nophoto.gif";
if (Request.QueryString["EI"] != null && Convert.ToInt32(Request.QueryString["EI"].ToString()) > 0)
{
this.Load_PersonnelRec(Convert.ToInt32(Request.QueryString["EI"].ToString()));
}
else
{
this.lblChangeDirectionHead.Enabled = false;
this.lblChangeDirections.Enabled = false;
this.lbSchedules.Disabled = true;
}
}
The page lifecycle does the following (plus other steps irrelevant to your question):
OnInit
Populate controls from ViewState (during postback)
Set the selected values (during postback)
Page_Load
You need to have ViewState enabled so it can populate the list before it "selects" the item. In this case, make sure you don't repopulate in Page_Load and lose the selected value. Do something like if (!IsPostback) { // Populate }
Otherwise, you have to populate the list manually in the OnInit event on every page request. Page_Load is too late in the lifecycle, so the selected item is lost.
Edit:
The DropDownList must also have valid values set (separate from the text displayed in the browser). This is done through the DataValueField property. Each value must be unique, otherwise only the first duplicate item will ever be selected. If you look at the HTML source in your browser, you should have:
<select>
<option value="unique_value1">Displayed text1</option>
<option value="unique_value2">Displayed text2</option>
</select>
The unique values are used for selecting the right item on the server side.
Are u using a Master Page? If so, remember to put the EnableViewState on true in the master page.

CheckedChanged event for checkbox not firing for dynamic checkboxes

I seem to be having an issue getting the event handler for a group of dynamic checkboxes. The code is posted here. I thought this would be pretty straight forward, the checkboxes do not appear in a repeater, datagrid, etc. They appear in a table which is located inside a div which positioned in the center of the screen. Any help would greatly appreciated.
foreach (SelectAssignedRolesByUserResult role in assignedRoles)
{
CheckBox cb = new CheckBox();
cb.ID = string.Format("CheckBox_{0}_{1}", role.role_nm, role.role_id);
cb.Text = role.role_nm;
cb.Attributes.Add("role_id", role.role_id.ToString());
cb.Attributes.Add("assigned_role_id", role.assigned_role_id.ToString());
cb.Checked = (role.assigned_role_id > 0);
cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
TableCell cell = new TableCell();
TableRow row = new TableRow();
cell.Controls.Add(cb);
row.Cells.Add(cell);
TableAssignedRoles.Rows.Add(row);
}
You don't mention where the code that dynamically adds the checkboxes is called. I'm guessing you put this in the Page_Load event handler, or in a sub that is called from within Page_Load.
If so, move it from Page_Load to Page_Init.
This is a very non-technical explanation of the reasoning for this:
This is because whether or not the controls are selected happens when the page parses the Viewstate. In the page lifecycle, the Page_Init loads the initial controls, then the viewstate is applied, and then the Page_Load fires.
Added
And don't forget to add
cb.AutoPostBack = true;
Can we see some more code? At what point in the lifecycle are you calling the above code?
If you're not recreating the checkboxes in exactly the same way on every postback, such that each Checkbox is assigned the same ID and can load ViewState properly, you'll lose your event handlers.

Resources