ASP.NET DropDownList SelectedValue property not being set immediately - asp.net

I have an ASP.NET webform on which I use a DropDownList control to allow the user to select an item and see related results. For some reason when I set the SelectedValue property of the DropDownList the value it's set to is not immediately available.
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.SelectedValue = "5";
BindView();
}
}
protected void BindActivities()
{
DataClassesDataContext dc = new DataClassesDataContext();
var query = from activity in dc.Activities
where activity.AssignedTo == Convert.ToInt32(DropDownList1.SelectedValue);
GridView1.DataSource = query;
GridView1.DataBind();
}
In the previous code I get an error that DropDownList1.SelectedValue is null. The wierd thing is that if I comment out the code that uses DropDownList1.SelectedValue and let the page load, DropDownList1 is actually set to value 5. So it looks like it's getting set correctly but is just not immediately available. The debugger confirms that DropDownList.SelectedValue is not set to 5 immediately after the line of code that sets it.
Any ideas what is going on here?

Are you setting the value before you have bound the dropdown list?

Yes the user above is right
if (!Page.IsPostBack)
{
BindView();
DropDownList1.SelectedValue = "5";
}
... should work just fine.
There is no such thing as a delay in execution, just the order of execution.

Related

Fields not changing in Formview when moving Pagination

I have a formview that on page load makes a call to a sql server and retrieves 5 records which I want the formview to paginate though.
I have sucessfully connected to the db, filled a dataset, and returned data when the web page renders. The problem is that when I move to a new page, the data does not change in the databound field.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
conn = new SqlConnection(connstr);
ds = new DataSet();
da = new SqlDataAdapter("call to stored proc", conn);
try
{
conn.Open();
da.Fill(ds, "m");
FormView1.DataSource = ds;
FormView1.DataKeyNames = new string[] { "PropKey" };
FormView1.DataBind();
}
catch (Exception ex)
{
Result = ex.Message;
}
finally
{
conn.Close();
}
}
Next when the paginate buttons are clicked I have this:
protected void FormView1_PageIndexChanging1(object sender, FormViewPageEventArgs e)
{
FormView1.PageIndex = e.NewPageIndex;
}
Please help,
Thanks
You will need to bind the data to the FormView just after setting the new page index like below.
protected void FormView1_PageIndexChanging1(object sender, FormViewPageEventArgs e)
{
FormView1.PageIndex = e.NewPageIndex;
BindFormViewData();
}
This is required because the FormView only displays the data for the active record and does not store any other records from the datasource, so upon change of the page index, the datasource is required to be bound again. See: Paging in a FormView Web Server Control
From the above link:
If the FormView control is bound to a data source control, or to any
data structure that implements the ICollection interface (including
datasets), the control gets all the records from the data source,
displays the record for the current page, and discards the rest. When
the user moves to another page, the FormView control repeats the
process, displaying a different record.
Hope this helps.

Control caused the post back

I have a form that contains a dropdownlist,
on index changed method,i will call my user control class .cs with parameters choosen by the user, when im putting my code inside the index changed like the code below, it doesnt work, which is a normal behavior:
protected void ResourceTypesDDL_SelectedIndexChanged(object sender, EventArgs e)
{
....
MyUsercontrol c = new MyUSercontrol(....);
this.panel.controls.add(c);
}
thats why i have to put the code inside my onload method, but the thing is how can i know if it is the ddl that caused the post back? is there a propertie? or should i use page.Request.Params.Get("__EVENTTARGET") technic ?
Thanks alot !
If your MyUserControl is really user control, that means .ascx file, you should use this:
Page.LoadControl("~/Controls/MyUserControl.ascx")
instead of creating the instance of the control by calling constructor directly.
protected void ResourceTypesDDL_SelectedIndexChanged(object sender, EventArgs e) {
....
var c = Page.LoadControl("~/Controls/MyUserControl.ascx");
this.panel.controls.add(c);
}
EDIT:
But of course, after every other post back, you will lose this control. So you should also make sure that you will create all dynamic controls during OnLoad event.
set the property autoPostBack=true on the dropdownlist in order for the page to postback
Or use the below function to get the post back control on the page_load
private string GetPostBackControl()
{
string retVal = string.Empty;
try
{
string ctrlname = Page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
Control ctrl = this.Page.FindControl(ctrlname);
if (ctrl != null)
{
retVal = ctrl.ID;
}
}
}
catch (Exception ex) { ManageException(ex, ShowGeneralErrorMessage); }
return retVal;
}
Try setting AutoPostBack="True" property of drop down list. After setting this property when you select an item in list it will automatically do the postback and your event ResourceTypesDDL_SelectedIndexChanged will be fired.

Why is my DropDownList empty on Postback?

I've looked at answers to some similar question but I still can't seem to figure this out. I think I'm misunderstanding something about how ASP.NET works.
In the standard ASP.Net 4.0 'Create a new Account' form, I've added a DropDownList containing Roles to be selected for the new account. in the aspx page, the control looks like this:
<asp:DropDownList ID="RoleList" Width="100px" runat="server"></asp:DropDownList>
I am then populating the List in the Page_Load Event:
protected void Page_Load(object sender, EventArgs e)
{
RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
if (Page.IsPostBack)
{
return;
}
//Set the Role List Selections
DropDownList roleList = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("RoleList");
//set the role list
String[] roles = Roles.GetAllRoles();
foreach (String role in roles)
{
roleList.Items.Add(new ListItem(role, role));
}
}
I can see/select a role from the generated html. The problem arises when the 'Submit' button for creating a User is clicked:
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
string continueUrl = RegisterUser.ContinueDestinationPageUrl;
if (String.IsNullOrEmpty(continueUrl))
{
continueUrl = "~/";
}
//set user role
DropDownList roleList = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("RoleList");
Roles.AddUserToRole(RegisterUser.UserName, roleList.SelectedValue);
Response.Redirect(continueUrl);
}
Here, The roleList object contains zero items, and has no selected values. Somehow, I am losing the populating items between selection of the item, and the submit. Any idea what I'm doing wrong?
Put your dropdownlist loading into the OnInit function instead - then it should be loaded properly when RegisterUser_CreatedUser is called:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//Set the Role List Selections
DropDownList roleList = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("RoleList");
//set the role list
String[] roles = Roles.GetAllRoles();
foreach (String role in roles)
{
roleList.Items.Add(new ListItem(role, role));
}
}
I had a similar issue that change of radio button selection would auto postback the page and the dropdown list items would disappear after the page is back.
Solution
Check IIS -> Your WebSite -> Pages & Controls -> Enable Viewstate & Enable Sessionstate should be set to true.
Hope this helps.
The code below bypasses the proper databinding on the page load.
if (Page.IsPostBack)
{
return;
}
You need to bind this control each time so that the values are present when click events are called. You may also get event errors for operating on selected items that are no longer present.
Did you try embracing your binding with the following condition?
if (!Page.IsPostBack)
{
//Binding goes here
}

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

I'm using XmlDataSource as the datasource for a dropdownlist.
Now I want to set the SelectedValue of the drop down when the page initially loads. I have tried the OnDataBound event of the drop down in which I could see the total items. But setting the SelectedValue didn't work. InOnDataBinding event, I couldn't even see the total items probably because the list isn't bound yet?
How can I set the selected index based on a value?
This seems to work for me.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataBind(); // get the data into the list you can set it
DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
}
}
DropDownList1.Items.FindByValue(stringValue).Selected = true;
should work.
This is working code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataTextField = "user_name";
DropDownList1.DataValueField = "user_id";
DropDownList1.DataSource = getData();// get the data into the list you can set it
DropDownList1.DataBind();
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("your default selected text"));
}
}
Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?

LINQ and paging with a listview

I have a page with a listview control and a datapager control. The listviews datasource is set programatically using this code:
Dim dal as new dalDataContext
Dim bookmarks = From data In dal.getData(userid)
listview1.DataSource = bookmarks
listview1.DataBind()
When i test this page in a browser it comes up with the error: 'ListView with id 'listview1' must have a data source that either implements ICollection or can perform data source paging if AllowPaging is true.'
How can i implement paging in this scenario?
Thanks
Try
listview1.DataSource = bookmarks.ToArray()
I had the same problem this week.
An answer to the click-twice problem that the OP subsequently encountered - move the Databind to the OnPreRender event handler:
protected void Page_PreRender(object sender, EventArgs e)
{
listview1.DataBind();
}
or maybe create a page properties changing and bindlistview there.
protected void lv_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
//set current page startindex, max rows and rebind to false
DataPager dp = lvNews.FindControl("lvDataPager1") as DataPager;
dp.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
BindListView();
}

Resources