ASP.NET - DropDown list problem with the selected value

Asked By mostafa hamdy on 26-Jun-12 09:15 AM
Earn up to 10 extra points for answering this tough question.
Hello All
I have some web site build in asp.net 4 and contains some web page have a dropdow list like the following:


<ASP:DropDownList ID="ddlCustomer" runat="server" CssClass="StylDropDownList1" DataSourceID="ObjectDataSource1"

 DataTextField="Name" DataValueField="ID" >

 <asp:ListItem Value="0" meta:ResourceKey="Choose" Selected="True"></asp:ListItem>

 </ASP:DropDownList>

  


<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="Get" TypeName="UniSoft.ACTCRM.BusinessLayer.CustomerManager">




</asp:ObjectDataSource>


and after the data source bind this controls it becomes like the following:

<option selected="selected" value="0">Choose...</option>
<option value="1">Ahmed ALi</option>
<option value="2">Emad Ahmed</option>
<option value="5">sas</option>
<option value="7">aaaaaaaa</option>
<option value="12">test</option>
<option value="13">ali </option>
<option value="14">hamada</option>
<option value="16">alihg</option>
<option value="17">Test customer</option>
<option value="19">hamada 2000</option>
<option value="20">Mustafa Hamdy</option>
<option value="21">Esmael</option>
<option value="22">Mircosoft</option>
<option value="23">ACT</option>
<option value="24">GizaSystems</option>
<option value="25">CompuTech</option>
<option value="26">MrcoTech</option>
<option value="27">QNet</option>
<option value="28">kkk</option>
<option value="29">3www</option>
<option value="32">sama</option>
<option value="33">NewOne</option>
<option value="34">Yousry</option>
<option value="35">Lila</option>
<option value="36">Omar Ahmed</option>
<option value="37">Moshen</option>
<option value="39">yasser</option>
<option value="40">Unisoft</option>
<option value="41">mostafa Hamdy</option>
<option value="42">gdfgdfgdfg</option>
<option value="43">hhhhhhhhhhhhhhhhhhh</option>
<option value="44">mostafaHamdy123</option>
<option value="45">woooooooooooooooooooow</option>
<option value="46">ahmed abdullhameen</option>

when I save the selected value in the DB correctly I wish to display it in dropdown list control I do like the following in the page Load:




string Mode = Request.QueryString["Mode"];


string ID = Request.QueryString["ID"];


if(!Page.IsPostBack)

{

if(Mode == "Edit")

{

FillData(


int.Parse(ID));


}

}



protected void FillData(int Id)


{

devMngr = new DeviceManager().GetByID(Id);


if (devMngr != null)  

{

ddlCustomer.SelectedValue = devMngr.CustomerID.ToString()//the value from data base is 12;

}
}
but after I do the above I found that the ddlCustomer.SelectedValue is 0 ?!!!!!
please if any body get what I mean and can help me please send me or tell me about some URL may help me to solve this issue
regards
Mostafa

Jitendra Faye replied to mostafa hamdy on 26-Jun-12 09:50 AM
Are you binding DropDownList in page_Load() event if yes then bind like this-

if(!IsPostBack)
  {
    //Bind DropDownList
  }


2nd thing after setting value for dropdownList check are you rebinding again id yes then it may be possible that value is replacing,
Vikram Singh Saini replied to mostafa hamdy on 26-Jun-12 12:35 PM
Hi,

In your dropdownlist declaration:

<ASP:DropDownList ID="ddlCustomer" runat="server" CssClass="StylDropDownList1" DataSourceID="ObjectDataSource1"
 DataTextField="Name" DataValueField="ID" >
 <asp:ListItem Value="0" meta:ResourceKey="Choose" Selected="True"></asp:ListItem>
</ASP:DropDownList


you have set to keep selected the Choose value that is the 0 (zero) index value.

You shared with us, "when I save the selected value in the DB correctly I wish to display it in dropdown list control I do like the following in the page Load:"

if(!Page.IsPostBack)
{
    if(Mode == "Edit")
   {
     FillData(int.Parse(ID));
    }
}


And here is the problem, the FillData() method would be call if the Page is not posted back to the server. But for saving the selected values in database, the page is already posted back to the server. So I think the FillData() would not get chance for execution anyhow.

I think you are saving selected value in querystring ID as

string ID = Request.QueryString["ID"];

So we can modify our code as:

if (!String.IsNullOrEmpty(ID))
      {
          if(Mode == "Edit")
                   {
             FillData(int.Parse(ID));
                   }
      }


Now I hope it would work. Let us know the action result.
Chintan Vaghela replied to mostafa hamdy on 27-Jun-12 01:26 AM

Hi Frndz,

 

Functionality:  Set DropDown Value

 

 

To achieve this task,

 

When you assign Dropdown value then first you need to set SelectedIndex  value is -1

 

ddlCustomer.SelectedIndex = -1;

 

 

 

Chnage your FillData Logic as following way

 

Logic ::

 

protected void FillData(int Id)

 

{

devMngr = new DeviceManager().GetByID(Id);

 

if (devMngr != null

{

    ddlCustomer.SelectedIndex = -1;

    ddlCustomer.SelectedValue = devMngr.CustomerID.ToString();//the value from data base is 12;

}

}

 

 

 

 

Hope this helpful!

Thanks

 

 

 

help
I've got an ObjectDataSource populating a GridView control. One of the fields in the gridview is a TemplateField with a dropdownlist in the EditItemTemplate. How do I get the selected value from the dropdownlist to the ObjectDataSource to use as a parameter for a command? . . in the SDK: [CODE] <%@ Page language = "C to the GridView1.SelectedValue and it will know that the value will be from the dropdownlist selected value. Because you make it seem a lot easier than what I just posted int index = AuthorsGridView.EditIndex; GridViewRow row = AuthorsGridView.Rows[index]; TextBox lastName = (TextBox)row.FindControl("LastNameTextBox"); DropDownList StateName = (DropDownList)row.FindControl("state_edit"); e.NewValues["au_lname"] = lastName.Text; e.NewValues["state_name"] = StateName.SelectedItem.Value.ToString
Dear All I have it. Here is my code at the moment:- <tr> <td> Main Menu < / td> <td> <asp:DropDownList ID = "ddlMainPage" runat = "server" DataSourceID = "dsAdminMainMenus" DataTextField = "admin_menu_tit" DataValueField = "admin_menu_id" AutoPostBack = "True" EnableViewState = "False" OnDataBinding = "ddlMainPage_DataBound"> <asp:ListItem> - - Select - -< / asp:ListItem> < / asp:DropDownList> <asp:RequiredFieldValidator ID = "rfvddlMainPage" runat = "server" ControlToValidate = "ddlMainPage" ErrorMessage = "Please Select" InitialValue = "- - Select - -"> < / asp:RequiredFieldValidator asp:ObjectDataSource ID = "dsAdminMainMenus" runat = "server" SelectMethod = "GetAdminMainMenus" TypeName = "MenusBLL"> <SelectParameters> <asp:Parameter Name = "DataSource" DefaultValue = "Hamrun_DB" Type = "String" / > < / SelectParameters> < / asp:ObjectDataSource> < / td> < / tr> <tr> <td> Sub Menu < / td> <td> <asp:DropDownList ID = "ddlSubPage" runat = "server" DataSourceID = "dsAdminSubMenus" DataTextField = "admin_submenu_tit" DataValueField = "admin_submenu_id" EnableViewState = "False"> < / asp:DropDownList> <asp
master" %> <script language = "C#" runat = "server"> protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e) { string strProv = ((DropDownList)((FormView)sender).FindControl("ddlProvince")).SelectedValue; e.NewValues["Province"] = strProv; string strCity = ((DropDownList)((FormView)sender).FindControl("ddlCity")).SelectedValue; e.NewValues["City"] = strCity; e.Cancel = false; } protected void ddlProvince_DataBound object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; FormView frmV = (FormView)ddl.NamingContainer; if (frmV.DataItem ! = null) { string strProvince = ((DataRowView)frmV.DataItem)["Province"] as string; ddl.ClearSelection(); ListItem lm = ddl.Items.FindByValue(strProvince); if (lm = = null) { ((DataRowView)frmV.DataItem)["Province"] = ""; } else { lm.Selected = true; } } ddl = (DropDownList)frmV.FindControl("ddlCity"); if (ddl ! = null) ddl.DataBind(); } protected void ddlCity_DataBound(object sender, EventArgs e DropDownList ddl = (DropDownList)sender; FormView frmV = (FormView)ddl.NamingContainer; if (frmV.DataItem ! = null) { string strCity = ((DataRowView)frmV.DataItem
master" %> <script language = "C#" runat = "server"> protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e) { string strProv = ((DropDownList)((FormView)sender).FindControl("ddlProvince")).SelectedValue; e.NewValues["Province"] = strProv; string strCity = ((DropDownList)((FormView)sender).FindControl("ddlCity")).SelectedValue; e.NewValues["City"] = strCity; e.Cancel = false; } protected void ddlProvince_DataBound object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; FormView frmV = (FormView)ddl.NamingContainer; if (frmV.DataItem ! = null) { string strProvince = ((DataRowView)frmV.DataItem)["Province"] as string; ddl.ClearSelection(); ListItem lm = ddl.Items.FindByValue(strProvince); if (lm = = null) { ((DataRowView)frmV.DataItem)["Province"] = ""; } else { lm.Selected = true; } } ddl = (DropDownList)frmV.FindControl("ddlCity"); if (ddl ! = null) ddl.DataBind(); } protected void ddlCity_DataBound(object sender, EventArgs e DropDownList ddl = (DropDownList)sender; FormView frmV = (FormView)ddl.NamingContainer; if (frmV.DataItem ! = null) { string strCity = ((DataRowView)frmV.DataItem
easily filter On gridviewrowdatabound event, Find the dropdown list and follow this: / / here get the dropdownlist control from gridview using FindControl while (DropDownList1.Items.IndexOf( new ListItem ( "" )) ! = -1) { DropDownList1.Items.Remove( "" ); } it will remove all null values from the dropdown you have if(Reader[0].ToString().Trim() ! = "") { DropDown1.Items.Add(Reader[0].ToString()); } } Hi, You could use objectdatasource as your datasource. Create a funtion to your class then select it in objectdatasource, lastly bind it to your dropdownlist. < asp:DropDownList ID = "DropDownList1" runat = "server" AppendDataBoundItems = "True" DataSourceID = "ObjectDataSource1" DataTextField = "Yourcurrentselection" DataValueField = "youruniqueidentity" > < / asp DropDownList > < asp:ObjectDataSource ID = "ObjectDataSource1" runat = "server" SelectMethod = "bindTempData" TypeName = "tempdata" > < / asp:ObjectDataSource > Hope this will help you
Know ASP.NET 06-Jun-13 10:06 AM How to set a value in dropdownlist in ASP.NET. . . HI <%@ Page Language = ”C#” %> <! DOCTYPE html PUBLIC “ - / / W3C / / DTD XHTML 1 . 0 Identity.Name)); } < / script > < html xmlns = ” http: / / www . w3 . org / 1999 / xhtml ” > < head runat = ” server ” > < title > DropDownList Initialize < / title > < / head > < body > < form id = ” form1 ″ runat = ” server ” > < div > < asp:DropDownList ID = ” DropDownListUser ” runat = ” server ” DataSourceID = ” ObjectDataSourceUser ” DataTextField = ” UserName ” DataValueField = ” UserName ” OnDataBound = ” DropDownListUser_DataBound ” > < / asp:DropDownList > < asp:ObjectDataSource ID = ” ObjectDataSourceUser ” runat = ” server ” SelectMethod = ” GetMembers ” TypeName = ” MembershipUtilities . MembershipUserODS ” > < SelectParameters > < asp:Parameter Name = ” sortData ” Type String ” / > < / SelectParameters > < / asp:ObjectDataSource > < / div > < / form > < / body > < / html > hi. . t first make sure that your DDL is getting correct case which is working file for me. . here is my aspx page I have a DropdownList and I am binding it with SqlDataSource from my Category Table with a query <Select CategoryID, Name from Category> < form id = "form1" runat = "server" > < div > < asp:DropDownList ID = "DropDownList1" runat = "server" DataSourceID = "SqlDataSource1" DataTextField = "Name" DataValueField = "CategoryID" > < / asp:DropDownList > < br / > < asp:TextBox
SortDirection direction; / / Create the sort expression from the values selected / / by the user from the DropDownList controls. Multiple / / columns can be sorted by creating a sort expression / / that contains a comma id = "form1" runat = "server" > <h3> GridView Sort Example< / h3> <table> <tr> <td> Sort by : <asp:dropdownlist ID = "SortList1" runat = "server" > <asp:listitem Selected = "true" > CustomerID< / asp:listitem> <asp:listitem> CompanyName< / asp:listitem> <asp:listitem> Address< / asp:listitem> <asp:listitem> City< / asp:listitem> <asp:listitem> PostalCode< / asp:listitem> <asp:listitem> Country< / asp:listitem
default value inside same function where you are binding dropdown box. / / Use Below Code. . . / / Your DropDownList In ".aspx" File < asp:DropDownList id = "DDL" runat = "server" > < asp:ListItem Selected = "True" Value = "Select" Text = "Please Select" / > < asp:ListItem Value = "aaa" Text = "aaa" / > < asp:ListItem Value = "bbb" Text = "bbb" / > < asp ListItem Value = "ccc" Text = "ccc" / > < / asp:DropDownList > / / Now When You Want To Set First Value Again At Runtime Then Use Below Code use either FindByValue() or FindByText() method of the items collection. If found, it returns the / / ListItem otherwise, the method returns null. / / On your Save Button Click Event When User Will Save
in asp.net HI use this < ajaxToolkit : ComboBox ID = "ComboBox1" runat = "server" AutoPostBack = " False " DropDownStyle = " DropDownList " AutoCompleteMode = " SuggestAppend " CaseSensitive = " False " CssClass = " " ItemInsertLocation = " Append " . . . > hi, CascadingDropDown is an ASP.NET AJAX extender that can be attached to an ASP.NET DropDownList control to get automatic population of a set of DropDownList controls. Each time the selection of one the DropDownList controls changes, the CascadingDropDown makes a call to a specified web service to retrieve the list of values for the next DropDownList in the set. check this and let me know < asp:ScriptManager ID = "ScriptManager1" runat = "server cellspacing = "0" width = "500" > < tr > < td width = "100" > < b > Select Category :< / b > < / td > < td > < asp:DropDownList ID = "drdCategory" runat = "server" > < / asp:DropDownList > < ajaxToolkit:CascadingDropDown ID = "CascadingDropDown1" runat = "server" Category = "category" TargetControlID = "drdCategory" PromptText = "[Select Category]" LoadingText = "Loading ServiceMethod = "GetDropDownCategories" > < / ajaxToolkit:CascadingDropDown > < / td > < / tr > < tr > < td > < b > Select Product :< / b > < / td > < td > < asp:DropDownList ID = "drdProduct" runat = "server" OnSelectedIndexChanged = "drdProduct_SelectedIndexChanged" AutoPostBack = "True" > < / asp:DropDownList > < ajaxToolkit:CascadingDropDown ID = "CascadingDropDown2" runat