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.
C D 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 have a asp.net page that has a DDL tied to a ObjectDataSource. I want the DDL to display a blank in the list when the page is do I display a blank? Bill ASP.NET Discussions CategoryList.SelectedIndex (1) CategoryList.SelectedValue (1) DropDownList (1) AppendDataboundItems (1) ObjectDataSource (1) Load (1) Listitem (1) Window (1) * Bill Gower wrote, On 31-7-2007 0:06: In the designer is an ddl 'Object data source DataSourceID = "OdsCategoryNames" DataTextField = "categoryname" DataValueField = "category" runat = "server"> - -- -- -- -- -- -- keywords: ObjectDataSource, and, DropDownList description: I have a asp.net page that has a DDL tied to a ObjectDataSource
Hi! Wir haben hier größere Probleme mit einem DropDownList Server Control. In einem GridView werden Werte angezeigt, die aus einer ObjektDataSource stammen. Im Edit-Modus muss eines der Felder eine DropDownList anzeigen. Das DropDownList Server Control wird aus einem Bind-Ausdruck im Markup der Seite gespeist: DataSource = "<%# GetGesellschaften() %> GetGesellschaften liefert eine ListItemCollection. Bei der Erzeugung der ListItemCollection wird jedes ListItem mit einem Text und einem Value versehen. Das erste Problem besteht nun darin, dass im gerenderten HTML sowohl Text als auch Value auf die Text-Eigenschaft des ListItem eingestellt sind. Der Wert der Value-Eigenschaft geht irgendwie verloren. Als Folgefehler kann das SelectedValue der DropDownList nicht auf den Wert der Daten in der aktuellen Spalte des GridView eingestellt werden und
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
Hi, Is it possible to DISPLAY 2 columns somehow in a dropdownlist? For example: DataField Value = bound to ProductId DataField Display = Product Name and Product Number Thanks for any tips. Frank ASP.NET Discussions ListItemCollection (1) DropDownList (1) SqlDataReader (1) ListItem (1) Database (1) other than using a fixedwidth font and spaces, no. you can build want to have for example Patrick For anyone else, my solution was to use an ObjectDataSource that pointed to a custom class and method which does the database access, then returns a collection of ListItems to be used by the DropDownList. While pulling the fields from the SqlDataReader, I built ListItems and set the ListItem.Text = sqlDataReader["field1"].ToString() + " " + sqlDataReader["field2"].ToString(); Then I set the value: myListItem.Value = "RowID"; Then add each ListItem to an ListItemCollection, and return that Collection to the ObjectDataSource. Works like a charm. Frank
Framework I know, this is a very simple question but. . . I want to bound an ObjectDataSource with a DropDownList. And I want to do it like that : Residential Condominium Duplex Triplex Land Commercial Lands to the browser, all my spaces are trim. Why ? ASP.NET Discussions CategoriesBatiment.GetCategoriesBatiment (1) DropDownList (1) EventArgs (1) ListItem (1) Catbat.DescriptionGroupeFrancais (1) Control (1) Duplex (1) CategorieBatimentList (1) if you use a real Bruce I find on the net http: / / www.codeproject.com / aspnet / DropDownListOptionGroup.asp A dotNet dropdownList with the OptionGroup and Item based on what you say to me. It works very list of CategorieBatimentInfo. I loop in my collection and then add the objects in my dropdownlist. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { CategorieBatimentList catBats = CategoriesBatiment.GetCategoriesBatiment(); foreach (CategorieBatimentInfo catbat in catBats) { ListItem currentItem = new ListItem(catbat.DescriptionFrancais, catbat.CodeCategorie); currentItem.Attributes["OptionGroup"] = catbat.DescriptionGroupeFrancais; ddlCatBatiment.Items.Add(currentItem); } } } keywords: Stupid
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
Know ASP.NET 28-Oct-12 07:43 PM 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
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