?
Solved

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

Posted on 2012-08-23
15
Medium Priority
?
5,876 Views
Last Modified: 2012-08-25
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

0
Comment
Question by:tia_kamakshi
  • 7
  • 5
  • 3
15 Comments
 
LVL 23

Expert Comment

by:Christopher Kile
ID: 38326419
In your DropDownBox definition, you have an attribute named data-validate set to "isSelected".  What exactly is this?
0
 

Author Comment

by:tia_kamakshi
ID: 38326507
Here html 5 is used and this is from jquery

, isSelected = function (str) {
              return (str == '') ? false : true;
            }
0
 
LVL 23

Expert Comment

by:Christopher Kile
ID: 38326625
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:tia_kamakshi
ID: 38326674
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
 
LVL 23

Expert Comment

by:Christopher Kile
ID: 38326676
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
 

Author Comment

by:tia_kamakshi
ID: 38326688
Please read my comments above

I am using I.E., 8.0
0
 
LVL 23

Expert Comment

by:Christopher Kile
ID: 38326741
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
 
LVL 23

Expert Comment

by:Christopher Kile
ID: 38326752
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
 
LVL 16

Expert Comment

by:Rose Babu
ID: 38328055
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
 

Author Comment

by:tia_kamakshi
ID: 38328281
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
 
LVL 16

Expert Comment

by:Rose Babu
ID: 38328667
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
 

Author Comment

by:tia_kamakshi
ID: 38328827
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
 
LVL 16

Accepted Solution

by:
Rose Babu earned 2000 total points
ID: 38329190
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
 

Author Comment

by:tia_kamakshi
ID: 38331855
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
 

Author Closing Comment

by:tia_kamakshi
ID: 38331955
Writting EnableViewState="true" on page helped me

Thanks for your help
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses
Course of the Month17 days, 1 hour left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question