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

maddhacker24
maddhacker24 used Ask the Experts™
on
I'm learning ASP.net 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#.

Thanks!
<%@ 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>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
	<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
   	<ItemTemplate>
	      
	      <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>
        </asp:DropDownList>
        
        </ItemTemplate>
    </asp:Repeater>
</asp:Content>

-----------------------------------------

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
    {
        //initailize
        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
            else
            {
                //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)
                {
                    Response.Redirect("/");
		        	 }

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

                //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);
                myDataAdapter.Fill(myDataSet);
                //Bind the table to my Repeater.
                Repeater1.DataSource = myDataSet;
                Repeater1.DataBind();

                //Close my connection.
                myCommand.Connection.Close();
                myCommand.Connection.Dispose();     
            }
        }
       
        //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

Comment
Watch Question

Do more with

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

Author

Commented:
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();

Author

Commented:
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.
Hi,

Try this:

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

/Carl.


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();
        }
    }
}

Author

Commented:
Carl,

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

Author

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

((DropDownList)Repeater1.FindControl("listRating"));

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