Can't get value of DropDownList on my PostBack Event in my Code Behind C#

maddhacker24 used Ask the Experts™
I'm learning so im still a little cloudy with some concepts. I'm having an issue with the IsPostBack event. I'm trying to get the value of my DropDownList on PostBack so that I can do some database stuff when a user selects a value from the DropDownList but I cant seem to properly attain the value.  I attached my Front End and Code Behind.  Also, if you see that I am doing anything the wrong way, feel free to point it out.

Please provide any solutions in C#.

<%@ Page Title="" Language="C#" MasterPageFile="~/DH.Master" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="DH._default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
	<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
	      <asp:Label ID="lblRating" runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "Rating")%>"></asp:Label>

         <asp:DropDownList ID="listRating" AutoPostBack="true" style="font-size: 11px;" runat="server">
	         <asp:ListItem Value="1">1</asp:ListItem>
   	 		<asp:ListItem Value="2">2</asp:ListItem>
            <asp:ListItem Value="3">3</asp:ListItem>
            <asp:ListItem Value="4">4</asp:ListItem>
            <asp:ListItem Value="5">5</asp:ListItem>
            <asp:ListItem Value="6">6</asp:ListItem>
            <asp:ListItem Value="7">7</asp:ListItem>
            <asp:ListItem Value="8">8</asp:ListItem>
            <asp:ListItem Value="9">9</asp:ListItem>
            <asp:ListItem Value="10">10</asp:ListItem>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace DH
    public partial class _default : System.Web.UI.Page
        SqlConnection myConnection;
        SqlCommand myCommand;
        DataView myDataView = new DataView();
        DateTime TodaysDate = DateTime.Now;
        string sMonth;
        string sDay;
        string sYear;
        string DayDate;
        //SQL 2008 Databse Connection string from Web.Config
        string ConnectionString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)

            if (Page.IsPostBack)
                string sRating = ((DropDownList)this.Page.FindControl("listRating")).SelectedItem.Value.ToString();

	        //If the url has the Month/Day/Year in it then build DayDate.
            if (Request.QueryString["Month"] != null && Request.QueryString["Day"] != null && Request.QueryString["Year"] != null)
                sMonth = Request.QueryString["Month"];
                sDay = Request.QueryString["Day"];
                sYear = Request.QueryString["Year"];
                DayDate = sMonth + "/" + sDay + "/" + sYear;
            //Today's Date
                //Get Today's Month, Day, and Year
                sMonth = TodaysDate.Month.ToString();
                sDay = TodaysDate.Day.ToString();
                sYear = TodaysDate.Year.ToString();
                DayDate = sMonth + "/" + sDay + "/" + sYear;

            //If the URL contains a valid date...
            if (IsDate(DayDate) == true)
                //If the URL contains a Date that is > Today's Date...Send them to home page!
                if (Convert.ToDateTime(DayDate) > TodaysDate)

                //Open a Connection to SQL Server.
                myConnection = new SqlConnection(ConnectionString);

                //Set up my Stored Procedure.
                myCommand = new SqlCommand("sp_GetPicture", myConnection);
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.Parameters.AddWithValue("@DayDate", DayDate);

                //Execute the Stored Procedure using a DataAdapter
                DataSet myDataSet = new DataSet();
                SqlDataAdapter myDataAdapter = new SqlDataAdapter(myCommand);
                //Bind the table to my Repeater.
                Repeater1.DataSource = myDataSet;

                //Close my connection.
        //Access the Data in my Repeater control.
        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
            //Loop through each row in the dataset.
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                DataRowView row = e.Item.DataItem as DataRowView;

                //Get database values here.
                int CommentCount = Convert.ToInt32(row["CommentCount"]);
                DateTime DayDate = Convert.ToDateTime(row["DayDate"]);
                int Rating = Convert.ToInt32(row["Rating"]);
        //Function to check for Valid Date
        public static bool IsDate(string strDate)
            DateTime outDate;
            return DateTime.TryParse(strDate, out outDate);

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®


I forgot to mention the following error that I am getting on PostBack.

"Object reference not set to an instance of an object."
string sRating = ((DropDownList)this.Page.FindControl("listRating")).SelectedItem.Value.ToString();
string sRating = listRating.SelectedItem.Value.ToString();


Sorry AlfredRobot, that does not work. I need to use FindControl since the DropDownList is within a repeater.

It throws the following error: The name 'listRating' does not exist in the current context.
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

ok. if in the functin protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e),
you should be able to use
dropdownlist ddl = (dropdownlist)e.Item.FindControl("listRating");
to get the control.
not sure in the page_load how to do it exactly.

Try this:

if (Page.IsPostBack)
                DropDownList listRating = (DropDownList)Repeater1.FindControl("listRating");
                string sRating = listRating.SelectedItem.ToString();


or try this:

Repeater rp1 = (Repeater)page.FindControl("Repeater1");

foreach(Control oControl in rp1.Controls){
    if(oControl is DropDownList){
        if((DropDownList)oControl.ID == "listRating"){
             string sRating = oControl.SelectedItem.Value.ToString();



I  get the following error:  Object reference not set to an instance of an object.
string sRating = listRating.SelectedItem.ToString();


Found the problem. I needed to add an extra parentheses around the start and end.


Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial