Unable to get selected value from dropdownlist when submit button is clicked

Hi Experts,

I am working on ASP.Net2.0 using C#

I have a dropdownlist on my aspx page. on click of submit button, I am not able to read the selected value. It is always giving first value in the dropdown list.

i.e., Select a service

Please let me know that why I am not able to read the selected value from dropdownlist.

Please help me getting the selected value from dropdownlist

Please find my aspx and code behind code below

ASPX CODE:
<asp:DropDownList ID="ddlServiceOfInterest" runat="server" class="js-required" data-validate="isSelected" AppendDataBoundItems="true"></asp:DropDownList> 
<asp:Button ID="btnSubmit" Text="Send" runat="server" OnClick="btnSubmit_Click" />

Open in new window


CODE BEHIND:
protected void Page_Load(object sender, EventArgs e)
    {
        fillServicesDropDown();        
    }

    #region Submit Button Click
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        RequestQuote requestQuote = getRequestQuoteDetail();        
    }
    #endregion

    #region Get Request a Quote Details
    private RequestQuote getRequestQuoteDetail()
    {
        RequestQuote requestQuote = new RequestQuote();

        requestQuote.Service = ddlServiceOfInterest.SelectedItem.ToString();
        requestQuote.Message = txtMessage.Text;

        return requestQuote;
    }
    #endregion

    
    #region Fill Service Dropdownlist
    private void fillServicesDropDown()
    {
        string strSelectedText = string.Empty;

        if (!Page.IsPostBack)
        {
            strSelectedText = ddlServiceOfInterest.SelectedValue;
        }

        XmlDocument doc = new XmlDocument();
        try
        {
            doc.Load(Server.MapPath("~/english/include/xml/brandsnews.xml"));

            XmlNodeList nodeList = doc.SelectNodes("brandsnews/news");
            foreach (XmlNode node in nodeList)
            {
                string strValue = string.Empty;
                string strNewsID = string.Empty;
                try
                {
                    strValue = node.Attributes["name"].Value;
                    strNewsID = node.Attributes["newsID"].Value;

                    if ((!(string.IsNullOrEmpty(strValue)) && (!(string.IsNullOrEmpty(strNewsID)))))
                    {
                        ListItem lstItem = new ListItem(strValue, strNewsID);
                        ddlServiceOfInterest.Items.Add(lstItem);
                    }
                }
                catch (Exception ex2) { }
            }
        }
        catch (Exception ex)
        {
            Logger.Error("{0}: Error occured in Retrieving brands News - Check xml at path english/include/xml/brandsnews.xml ", ex.Message);
        }

        ddlServiceOfInterest.Items.Insert(0, new ListItem("Select a service", ""));

        if (!Page.IsPostBack)
        {
            ddlServiceOfInterest.SelectedValue = strSelectedText;
        }
        else
        {
            ddlServiceOfInterest.SelectedIndex = 0;
        }
    }
    #endregion
    

Open in new window

tia_kamakshiAsked:
Who is Participating?
 
Rose BabuSenior Team ManagerCommented:
Here is my sample page that will read the news details from the xml and populating it into a dropdownlist.

on submitting, the selected item's text and value is read and displayed.

//	Default5.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <br />
        <asp:DropDownList ID="ddlServiceOfInterest" runat="server" Height="16px" Width="252px">
        </asp:DropDownList>
        <br />
        <br />
        <asp:Label ID="lblNews" runat="server" Text=""></asp:Label>
        <br />
        <br />
        <asp:Button ID="btnNews" runat="server" Text="Submit" OnClick="btnNews_Click" />
    </div>
    </form>
</body>
</html>

Open in new window

//	Default5.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;

public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            fillServicesDropDown();
        }
    }

#region Fill Service Dropdownlist
    private void fillServicesDropDown()
    {
        string strSelectedText = string.Empty;

        XmlDocument doc = new XmlDocument();
        try
        {
            doc.Load(Server.MapPath("brandsnews.xml"));

            XmlNodeList nodeList = doc.SelectNodes("brandsnews/news");
            foreach (XmlNode node in nodeList)
            {
                string strValue = string.Empty;
                string strNewsID = string.Empty;
                try
                {
                    strValue = node.Attributes["Name"].Value;
                    strNewsID = node.Attributes["newsID"].Value;

                    if ((!(string.IsNullOrEmpty(strValue)) && (!(string.IsNullOrEmpty(strNewsID)))))
                    {
                        ListItem lstItem = new ListItem(strValue, strNewsID);
                        ddlServiceOfInterest.Items.Add(lstItem);
                    }
                }
                catch (Exception ex2) { }
            }
        }
        catch (Exception ex)
        {
            //Logger.Error("{0}: Error occured in Retrieving brands News - Check xml at path english/include/xml/brandsnews.xml ", ex.Message);
        }

        ddlServiceOfInterest.DataBind();

        ddlServiceOfInterest.Items.Insert(0, new ListItem("Select a service", ""));        
    }
#endregion

    protected void btnNews_Click(object sender, EventArgs e)
    {
        //lblNews.Text = ddlServiceOfInterest.SelectedItem.Text;

        int cntItems = ddlServiceOfInterest.Items.Count; // VALUE IS COMING 0 HERE. LOOKS VALUE FILLED FROM XML IS LOST AT PRE RENDER or RENDER of the page
        if (cntItems != 0)
        {
            string strSelectedValue = ddlServiceOfInterest.SelectedItem.Value;
            string strSelectedName = ddlServiceOfInterest.SelectedItem.Text ;

            lblNews.Text = "Selected Value : " + strSelectedValue;
            lblNews.Text += "<br><br>Selected Name : " + strSelectedName;

        }

    }
}

Open in new window

//	brandsnews.xml

<?xml version="1.0" encoding="utf-8" ?>
<brandsnews>
  <news newsID="1" Name="New Title 1" />
  <news newsID="2" Name="New Title 2" />
  <news newsID="3" Name="New Title 3" />
  <news newsID="4" Name="New Title 4" />
</brandsnews>

Open in new window

Check this code.
0
 
Christopher KileCommented:
In your DropDownBox definition, you have an attribute named data-validate set to "isSelected".  What exactly is this?
0
 
tia_kamakshiAuthor Commented:
Here html 5 is used and this is from jquery

, isSelected = function (str) {
              return (str == '') ? false : true;
            }
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Christopher KileCommented:
Try the following code in your HTML to see if data-validate is supported within the browser in which you are testing:

<script>  
if (!'data-validate' in document.createElement('input') ) {  
    // do client/server side validation  
}  
</script>
0
 
tia_kamakshiAuthor Commented:
I have removed code
data-validate="isSelected"

and now code is:
<asp:DropDownList ID="ddlServiceOfInterest" runat="server" class="js-required"  AppendDataBoundItems="true"></asp:DropDownList>


still the same result

Please suggest
0
 
Christopher KileCommented:
Sorry, should read:

<script>   
if (!'data-validate' in document.createElement('select') ) {   
    // do client/server side validation   
}   
</script> 

Open in new window


What browser are you using?
0
 
tia_kamakshiAuthor Commented:
Please read my comments above

I am using I.E., 8.0
0
 
Christopher KileCommented:
You're only getting the .SelectedValue if there is no postback:

 if (!Page.IsPostBack)
        {
            strSelectedText = ddlServiceOfInterest.SelectedValue;
        }

Open in new window


Also, Page is incorrect reference here.  try:

 if (Me.IsPostBack)
        {
            strSelectedText = ddlServiceOfInterest.SelectedValue;
        }

Open in new window

0
 
Christopher KileCommented:
Also change it here:

if (!Page.IsPostBack)
        {
            ddlServiceOfInterest.SelectedValue = strSelectedText;
        }
        else
        {
            ddlServiceOfInterest.SelectedIndex = 0;
        }

Open in new window


becomes


if (Me.IsPostBack)
        {
            ddlServiceOfInterest.SelectedValue = strSelectedText;
        }
        else
        {
            ddlServiceOfInterest.SelectedIndex = 0;
        }

Open in new window

0
 
Rose BabuSenior Team ManagerCommented:
Are you binding the dropdown values in the page_load and not placed the binding inside the Page PostBack checking.

If so then put your binding process inside a page postback checking as shown below then check the selected value while postback

protected void Page_Load(object sender, EventArgs e)
{
	if (!Page.IsPostBack)
	{ 
		// Bind DropDownList
	}
}

Open in new window

Hope this will help you.
0
 
tia_kamakshiAuthor Commented:
Thanks for your replies. I have modified the code as advised. Please find my modified code below.
   
    When I select the value from dropdown and click submit button, then I see that dropdown list count is 0
   
    ddlServiceOfInterest.Items.Count; I checked it from quick watch.
   
    So, all values from the dropdown gets lost. Its because I have modified the following code in page load
    if (!Page.IsPostBack)
    {
      fillServicesDropDown();
    }
          
and on button click event below line throws exception as selected item is 0

    string strSelectedValue = ddlServiceOfInterest.SelectedItem.ToString();    

Please suggest
protected void Page_Load(object sender, EventArgs e)
    {

	    if (!Page.IsPostBack)
	    {
		fillServicesDropDown();
	    }
    }

Open in new window

 #region Submit Button Click
    protected void btnSubmit_Click(object sender, EventArgs e)
    {        
        string strSelectedValue = ddlServiceOfInterest.SelectedItem.ToString();     
    }
    #endregion

Open in new window

 
#region Fill Service Dropdownlist
    private void fillServicesDropDown()
    {
        string strSelectedText = string.Empty;

        if (!Page.IsPostBack)
        {
            strSelectedText = ddlServiceOfInterest.SelectedValue;
        }
        else
        {
            ddlServiceOfInterest.SelectedIndex = 0;
        } 


        XmlDocument doc = new XmlDocument();
        try
        {
            doc.Load(Server.MapPath("~/english/include/xml/brandsnews.xml"));

            XmlNodeList nodeList = doc.SelectNodes("brandsnews/news");
            foreach (XmlNode node in nodeList)
            {
                string strValue = string.Empty;
                string strNewsID = string.Empty;
                try
                {
                    strValue = node.Attributes["name"].Value;
                    strNewsID = node.Attributes["newsID"].Value;

                    if ((!(string.IsNullOrEmpty(strValue)) && (!(string.IsNullOrEmpty(strNewsID)))))
                    {
                        ListItem lstItem = new ListItem(strValue, strNewsID);
                        ddlServiceOfInterest.Items.Add(lstItem);
                    }
                }
                catch (Exception ex2) { }
            }
        }
        catch (Exception ex)
        {
            Logger.Error("{0}: Error occured in Retrieving brands News - Check xml at path english/include/xml/brandsnews.xml ", ex.Message);
        }

        ddlServiceOfInterest.Items.Insert(0, new ListItem("Select a service", ""));

        if (!Page.IsPostBack)
        {
            ddlServiceOfInterest.SelectedValue = strSelectedText;
        }
        else
        {
            ddlServiceOfInterest.SelectedIndex = 0;
        }
    }
    #endregion

Open in new window

0
 
Rose BabuSenior Team ManagerCommented:
Hi,

in your code, the binding code for the ddlServiceOfInterest dropdown is missing.

also you need to check the Page.IsPostBack in page_load.

Have the below updated code and update your process then test once.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;

public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            fillServicesDropDown();
        }
    }

    protected void btnNews_Click(object sender, EventArgs e)
    {
        lblNews.Text = ddlServiceOfInterest.SelectedItem.Text;
    }

#region Fill Service Dropdownlist
    private void fillServicesDropDown()
    {
        string strSelectedText = string.Empty;
        
        XmlDocument doc = new XmlDocument();
        try
        {
            doc.Load(Server.MapPath("~/english/include/xml/brandsnews.xml"));

            XmlNodeList nodeList = doc.SelectNodes("brandsnews/news");
            foreach (XmlNode node in nodeList)
            {
                string strValue = string.Empty;
                string strNewsID = string.Empty;
                try
                {
                    strValue = node.Attributes["name"].Value;
                    strNewsID = node.Attributes["newsID"].Value;

                    if ((!(string.IsNullOrEmpty(strValue)) && (!(string.IsNullOrEmpty(strNewsID)))))
                    {
                        ListItem lstItem = new ListItem(strValue, strNewsID);
                        ddlServiceOfInterest.Items.Add(lstItem);
                    }
                }
                catch (Exception ex2) { }
            }
        }
        catch (Exception ex)
        {
            Logger.Error("{0}: Error occured in Retrieving brands News - Check xml at path english/include/xml/brandsnews.xml ", ex.Message);
        }

        ddlServiceOfInterest.DataBind(); // THIS LINE IS MISSING IN YOUR CODE                

        ddlServiceOfInterest.Items.Insert(0, new ListItem("Select a service", ""));

    }
#endregion

}

Open in new window

Hope this will work. Try this.
0
 
tia_kamakshiAuthor Commented:
Thanks for your replies.

I have modified the code as suggested. Still the same issue. Please find my modified code below:

At the time of first page load, I can see all values is filled in the dropdown. But when button is clicked then all values filled at runtime is lost

Looks it is loosing at page pre-render or at the time of render of page

Please suggest

Thanks again

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
	{
		fillServicesDropDown();
	}
    }

    #region Submit Button Click
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int cntItems = ddlServiceOfInterest.Items.Count; // VALUE IS COMING 0 HERE. LOOKS VALUE FILLED FROM XML IS LOST AT PRE RENDER or RENDER of the page
        if (cntItems != 0)
        {
            string strSelectedValue = ddlServiceOfInterest.SelectedValue;
        }
    }
    #endregion


    #region Fill Service Dropdownlist
    private void fillServicesDropDown()
    {
        XmlDocument doc = new XmlDocument();
        try
        {
            doc.Load(Server.MapPath("~/english/include/xml/brandsnews.xml"));

            XmlNodeList nodeList = doc.SelectNodes("brandsnews/news");
            foreach (XmlNode node in nodeList)
            {
                string strValue = string.Empty;
                string strNewsID = string.Empty;
                try
                {
                    strValue = node.Attributes["name"].Value;
                    strNewsID = node.Attributes["newsID"].Value;

                    if ((!(string.IsNullOrEmpty(strValue)) && (!(string.IsNullOrEmpty(strNewsID)))))
                    {
                        ListItem lstItem = new ListItem(strValue, strNewsID);
                        ddlServiceOfInterest.Items.Add(lstItem);
                    }
                }
                catch (Exception ex2) { }
            }
        }
        catch (Exception ex)
        {
            Logger.Error("{0}: Error occured in Retrieving brands News - Check xml at path english/include/xml/brandsnews.xml ", ex.Message);
        }

        ddlServiceOfInterest.DataBind(); 

        ddlServiceOfInterest.Items.Insert(0, new ListItem("Select a service", ""));
    }
    #endregion

Open in new window

0
 
tia_kamakshiAuthor Commented:
Hi,

It works good, when I have excecuted your code in different R&D project.

But if I copy the same aspx code in my project. It stops working.

Even in the Page_PreInit the dropdown list count is 0. This is only happening after button click

        int cntItems = ddlServiceOfInterest.Items.Count;
       
What can be the possible reasons. Why this is not working on my project code, where it is required.

Please help in fixing the issue
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="request-a-quotee.aspx.cs" Inherits="english_request_a_quotee" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <br />
        <asp:DropDownList ID="ddlServiceOfInterest" runat="server" Height="16px" Width="252px">
        </asp:DropDownList>
        <br />
        <br />
        <asp:Label ID="lblNews" runat="server" Text=""></asp:Label>
        <br />
        <br />
        <asp:Button ID="btnNews" runat="server" Text="Submit" OnClick="btnNews_Click" />
    </div>
    </form>
</body>
</html> 

Open in new window



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

public partial class english_request_a_quotee : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            fillServicesDropDown();
        }
    }

    #region Fill Service Dropdownlist
    private void fillServicesDropDown()
    {
        string strSelectedText = string.Empty;

        XmlDocument doc = new XmlDocument();
        try
        {
            doc.Load(Server.MapPath("~/english/include/xml/brandsnews.xml"));

            XmlNodeList nodeList = doc.SelectNodes("brandsnews/news");
            foreach (XmlNode node in nodeList)
            {
                string strValue = string.Empty;
                string strNewsID = string.Empty;
                try
                {
                    strValue = node.Attributes["Name"].Value;
                    strNewsID = node.Attributes["newsID"].Value;

                    if ((!(string.IsNullOrEmpty(strValue)) && (!(string.IsNullOrEmpty(strNewsID)))))
                    {
                        ListItem lstItem = new ListItem(strValue, strNewsID);
                        ddlServiceOfInterest.Items.Add(lstItem);
                    }
                }
                catch (Exception ex2) { }
            }
        }
        catch (Exception ex)
        {
            //Logger.Error("{0}: Error occured in Retrieving brands News - Check xml at path english/include/xml/brandsnews.xml ", ex.Message);
        }

        ddlServiceOfInterest.DataBind();

        ddlServiceOfInterest.Items.Insert(0, new ListItem("Select a service", ""));
    }
    #endregion

    protected void btnNews_Click(object sender, EventArgs e)
    {
        //lblNews.Text = ddlServiceOfInterest.SelectedItem.Text;

        int cntItems = ddlServiceOfInterest.Items.Count; 
        if (cntItems != 0)
        {
            string strSelectedValue = ddlServiceOfInterest.SelectedItem.Value;
            string strSelectedName = ddlServiceOfInterest.SelectedItem.Text;

            lblNews.Text = "Selected Value : " + strSelectedValue;
            lblNews.Text += "<br><br>Selected Name : " + strSelectedName;
        }
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        int cntItems = ddlServiceOfInterest.Items.Count; 
        if (IsPostBack)
        {
            int cntItems2 = ddlServiceOfInterest.Items.Count; 
        }
    }

    protected override void OnUnload(EventArgs e){
        base.OnUnload(e);
        int cntItems = ddlServiceOfInterest.Items.Count; 
    }


}

Open in new window

0
 
tia_kamakshiAuthor Commented:
Writting EnableViewState="true" on page helped me

Thanks for your help
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.