Dropdownlist Databind automatically setting selected value? - c#

I filled a dropdownlist with active directory users, not a big deal and works great. The problem is it's setting <option selected="selected" value="user">User</option>
on the first one and won't let me change it in the code behind. Is there a way to keep it from automatically setting that selected="selected"?

<asp:DropDownList ID="dlst" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dlstvalues" DataTextField="name"
AppendDataBoundItems="true">
<asp:ListItem>-- Select --</asp:ListItem>
</asp:DropDownList>
Or this should work:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.AppendDataBoundItems = true;
DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
DropDownList1.SelectedIndex = 0;
}
}

It will automatically set the first one as selected. You have to enter a default value into the drop down list and set it to the first item.
ddlName.Items.Insert(0, new System.Web.UI.WebControls.ListItem("<--Select-->", "0"));

This is happning because you may be binding your dorpdown on page load.
And you may not be checking for postback
Doing so it will bind the values again and you will get the new items in the dropdown list.
The previous selected index will not remain.
You should bind this in !isPostBack
if (!Page.IsPostBack)
{
//bind data
}

Related

How to get selected value of item from dropdownlist inside formview?

I need to get the value of the selected item in a dropdown list that's inside the edit template of a formview control. The formview ID is "fvDocRvwrs".
Here's the markup for the dropdownlist:
<asp:DropDownList SelectedValue='<%# Bind("rvwStat") %>' runat="server" ID="rvwStatDdl" CssClass="form-control" DataSourceID="sdsStatuses" DataTextField="stat" DataValueField="statIdPk" AppendDataBoundItems="true" OnSelectedIndexChanged="rvwStatDdl_SelectedIndexChanged"><asp:ListItem Value="">--Please Select--</asp:ListItem></asp:DropDownList>
I'm just having some difficulty getting the SelectedValue using the onselectedindexchanged event of the dropdownlist. I am able to find the control using:
protected void rvwStatDdl_SelectedIndexChanged(object sender, EventArgs e)
{
var statVal = fvDocRvwrs.FindControl("rwStatDdl").ToString();
}
I just need to know how to populate a variable with the selected value.
I think you should cast as DropDownList after finding control
var statVal = ((DropDownList)fvDocRvwrs.FindControl("rwStatDdl")).SelectedValue.ToString();
You can access the SelectedValue property.
Try
protected void name_SelectedIndexChanged(object sender, EventArgs e){
DropDownList list = (DropDownList)sender;
string value = list.SelectedValue;}
Credit: Dropdownlist selected value at Selectedindexchanged event Frank Lee's answer

Store in a variable the SelectedValue of a DropDownList then call it

I am adding a user to a role in asp.net but i want to get the selected role from a dropdownlist. a single option is working for me but i need to implement a two choices dropD list.
public partial class Register : Page
{
protected void Selection_Change(object sender, EventArgs e)
{
var tr = TakeRole.SelectedValue; // store it in some variable
}
protected void CreateUser_Click(object sender, EventArgs e)
{
// code
if (result.Succeeded)
{
manager.AddToRole(user.Id, "SomeRoleName");
}
}
on aspx i have
<asp:DropDownList id="TakeRole" AutoPostBack="True" OnSelectedIndexChanged="Selection_Change" runat="server">
<asp:ListItem> Supplier </asp:ListItem>
<asp:ListItem Selected="True"> Customer </asp:ListItem>
</asp:DropDownList>
Please use a listbox on multi selection mode and restrict selection to 2 items. Else you can use dropdownlist with jQuery.
If you intend to use checkboxlist, then other than binding source, in check changed event count checked items to 2 and if more items are selected an alert is to be displayed.

Get the selected text (not selected value) of an asp:dropdownlist in code behind using C#

I need to read in the code behind the selected text (not the value) in the dataTextField of a dropdownlist that is nested in a FormView.
Here is my DDL:
<asp:DropDownList ID="DDL1" runat="server" DataSourceID="SQL1" dataTextField="name" DataValueField="IDname" CausesValidation="True" ClientIDMode="Static">
</asp:DropDownList>
And here is my code behind:
protected void UpdateButton_Click(object sender, EventArgs e)
{
DropDownList DDL1 = FV1.FindControl("DDL1") as DropDownList;
SQL3.UpdateParameters["ddlparam"].DefaultValue = DDL1.SelectedValue;
// Possible to get the text corresponding to the selectedValue?
}
So far so good. Now I want to get the text in the dataTextField corresponding to the selected value. Possible? and How?
Grab the text of the selected item with:
DDL1.SelectedItem.Text
you're looking for DDL.SelectedItem.Text MSDN

asp.net dropdownlist not updating selected value

I have a page with a gridview on it and a dropdown list which controls how many items per page the gridview will display.
The pageSize value of the gridview is controlled by this dropdown list and it gets saved to a cookie.
When the user loads the site the cookie is read so that it remembers what page size the user picked.
I have one problem and that is, if I pick another value on the dropdown list it does not update either cookie or dropdown list. It reverts back to the saved value.
This is the dropdown list created in the gridview pager template:
<PagerTemplate>
<asp:Table ID="Table3" runat="server" Width="100%">
<asp:TableRow>
<asp:TableCell HorizontalAlign="Left">
<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>
</asp:TableCell>
<asp:TableCell HorizontalAlign="Right" Width="10%">
Page Size
<asp:DropDownList runat="server" ID="ddlPageSize" AutoPostBack="true"
OnSelectedIndexChanged="ddlPageSize_SelectedIndexChanged" OnLoad="ddlPageSize_Load">
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>20</asp:ListItem>
<asp:ListItem>50</asp:ListItem>
<asp:ListItem>100</asp:ListItem>
</asp:DropDownList>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</PagerTemplate>
and this is where I try to load the value of the dropdown list from cookie:
protected void Page_Load(object sender, EventArgs e)
{
string pageSize = "10";
//Try and load the PageSize cookie from the user's machine and default to 10 records if none is found.
if (Request.Cookies["PageSize"] != null)
{
if (Request.Cookies["PageSize"]["Value"] != null)
{
pageSize = Request.Cookies["PageSize"]["Value"];
int _pageSize;
int.TryParse(pageSize, out _pageSize);
gvRecordsList.PageSize = _pageSize;
DropDownList ddlPageSize = (gvRecordsList.BottomPagerRow).FindControl("ddlPageSize") as DropDownList;
ddlPageSize.SelectedIndex = ddlPageSize.Items.IndexOf(new ListItem(pageSize));
}
}
else
gvRecordsList.PageSize = 10;
if (IsPostBack)
{
ApplyPaging();
}
else
{
gvRecordsList.DataSourceID = "RecordsListSqlDataSource";
gvRecordsList.DataBind();
}
}
The dropdown list index changed code:
protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlPageSize = (gvRecordsList.BottomPagerRow).FindControl("ddlPageSize") as DropDownList;
gvRecordsList.PageSize = int.Parse(ddlPageSize.SelectedValue);
Response.Cookies["PageSize"]["Value"] = ddlPageSize.SelectedValue;
Response.Cookies["PageSize"].Expires = DateTime.Now.AddDays(1d);
}
When I step through the code of the SelectedIndexChanged method, I can see that ddlPageSize.SelectedValue always contains the value from the cookie, 50, even though I select another value.
I guess the question is, where do I set the index of the dropdown list?
DropDownList ddlPageSize = (gvRecordsList.BottomPagerRow).FindControl("ddlPageSize") as DropDownList;
ddlPageSize.SelectedIndex = ddlPageSize.Items.IndexOf(new ListItem(pageSize));
The Page_Load event executes before the DropDownList SelectedIndexChanged event. And you are loading the cookie's value to the DropDownList on the PageLoad event.
I suggest you to try loading the cookie afterwards, on the OnPreRender event for example.
Or add a condition to your Page_Load logic, verifying if the PostBack is caused by the DropDownList:
DropDownList ddlPageSize = (gvRecordsList.BottomPagerRow).FindControl("ddlPageSize") as DropDownList;
bool isDDLPostingBack = Request["__EVENTTARGET"] == ddlPageSize.UniqueID;
if (Request.Cookies["PageSize"]["Value"] != null && !isDDLPostingBack)
{
...
}

Avoid Refreshing on Databound Dropdownlist

I am working on a metrics screen that will display several charts based on different groups in a database. Part of it uses a function that hides selected charts until the user clicks to display them.
The problem is this: I'm using a Databind on the dropdownlist, so every time I select a new group, the page refreshes and everything returns to its default state.
My question is this: Is there a way that I can avoid refreshing the page every time I select a new option from the dropdown list? If so, how? If not, is there a better way to create the dropdownlist and attach values to it? If I set AppendDataBoundItems to false, then I always get the selected value as the first item in the list.
Here's my code for the dropdownlist:
<asp:DropDownList ID="MinistryDropdown" OnSelectedIndexChanged="Selection_Change" AutoPostback="true" AppendDataBoundItems="true" runat="server"/>
Then C# code behind it is this:
public void Page_Load(object sender, EventArgs e){
MinistryDropdown.DataSource = CreateDataSource();
MinistryDropdown.DataTextField = "Description";
MinistryDropdown.DataValueField = "Description";
MinistryDropdown.DataBind();
...other code here...
}
ICollection CreateDataSource(){
DataTable Ministries = new DataTable();
Ministries = oDatabase.GetData(#"SELECT DISTINCT B.Description
FROM tblInvolvement AS A LEFT JOIN tblMinistries AS B
ON A.Activity = B.MinistryID");
DataView dv = new DataView(Ministries);
return dv;
}
Try to use the ASP.NET UpdatePanel. Just wrap your DropDownList in it, and it should works. Here is a quick example that I didn't test.
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="MinistryDropdown" OnSelectedIndexChanged="Selection_Change" AutoPostback="true" AppendDataBoundItems="true" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
On a final note, you will soon find out the limits of this solution, and later you might prefer to use Javascript instead.
I think the issue is that you are rebinding the data on Page_Load but you are not checking if !IsPostBack in other words, your code should look like this:
public void Page_Load(object sender, EventArgs e){
if(!IsPostBack)
{
MinistryDropdown.DataSource = CreateDataSource();
MinistryDropdown.DataTextField = "Description";
MinistryDropdown.DataValueField = "Description";
MinistryDropdown.DataBind();
...other code here...
}
}

Categories