Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Need help plz please, i have two DropDownLists (nested). I use SelectedIndexChanged event to populate the second DropDownList.

So, the problem is that i need to save the both values of DropDownLists to a database, i can do easily for the first DropDownList , but how to capture the second value ( DropDownList2.SelectedItem.Value)?

this is a part of my code ..
.
.
.
C#
protected void Page_Load(object sender, EventArgs e)
{
	if (Page.IsPostBack == false)
	{
		// create SqlConnection object
		string ConnectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
		SqlConnection myConnection = new SqlConnection(ConnectionString);
		// create SqlCommand object
		SqlCommand myCommand = new SqlCommand();
		myCommand.Connection = myConnection;
		try
		{
			myConnection.Open();
			myCommand.CommandText = "SELECT category_id, name FROM categories order by 2";
			// run query
			SqlDataReader myReader = myCommand.ExecuteReader();
			// set up the list
			DropDownList1.DataSource = myReader;
			DropDownList1.DataBind();
			// close the reader
			myReader.Close();
		}
		finally
		{
			// open the database connection
			myConnection.Close();
		}
	   
	}
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
	 // create SqlConnection object
	string ConnectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
	SqlConnection myConnection = new SqlConnection(ConnectionString);
	// create SqlCommand object
	string CommandText = "SELECT sub_cat_id, name, category_id FROM sub_category WHERE category_id = " + DropDownList1.SelectedItem.Value;
	SqlCommand myCommand = new SqlCommand(CommandText, myConnection);

	try
	{
		// open the database connection
		myConnection.Open();
		// run query
		SqlDataReader myReader = myCommand.ExecuteReader();
		// setup the GridView
		DropDownList2.DataSource = myReader;
		DropDownList2.DataBind();
		// close the reader
		myReader.Close();
	}
	finally
	{
		// open the database connection
		myConnection.Close();

	}		
}
Posted
Updated 5-May-11 3:43am
v2
Comments
mksharma38 5-May-11 9:38am    
at which stage u r ssaving drop down vale in db. u can get the value of second drop down in same manaer DropDownList2.SelectedItem.Value
mksharma38 5-May-11 9:42am    
u can aslo use DropDownList2.SelectedValue
or DropDownList2.Text
day_hard 5-May-11 9:57am    
forget the saving, if i display the value of DropDownList2.SelectedItem.Value in a lable like this:
Label1.Text = DropDownList2.SelectedItem.Value;
gives me a server error "Object reference not set to an instance of an object", rather than DropDownList1.SelectedItem.Value it's displayed well, i confused
Karthik. A 5-May-11 10:18am    
I guess you are trying to access DropDownList2 before populating it

You are more or less there. Just set the AutoPostBack property of the second drop down also to true and handle the selected index changed event. Now you can the selected values for both the drop downs and add it to the database.

If this is not what you intended to achieve, sorry. Please elaborate on what you expect.
 
Share this answer
 
Comments
fjdiewornncalwe 5-May-11 9:44am    
+5. I think you got it.
day_hard 5-May-11 10:01am    
sorry i tried to make the second dropdownlist also autopostback , but couldn't success to capture it's value after SelectedIndexChanged event done.
Karthik. A 5-May-11 10:05am    
Is the second drop down populated after you select an item in the first drop down?
day_hard 5-May-11 10:06am    
yes indeed, its populated successfuly
Karthik. A 5-May-11 10:13am    
I have created a sample, am posting it as another answer, check it out.... try to understand how it is done and try it yourself. Of course you could spend your time figuring this out, but seeing others code could also be a good exercise.
As i said before, use this as something to understand your mistakes and build on it. This is just a sample of how you could do it. I would be happy if you understand something out of this!

ASPX Markup:

XML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="SampleWebApp.test" %>

<!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>
        <asp:DropDownList ID="dd1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dd1_Changed"></asp:DropDownList>
        <br />
        <asp:DropDownList ID="dd2" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dd2_Changed"></asp:DropDownList>
        <br />
        <asp:Label ID="lbl1" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>



C# code-behind:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SampleWebApp
{
    public partial class test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                dd1.DataSource = Data.GetSource(5);
                dd1.DataTextField = "Text";
                dd1.DataValueField = "Value";
                dd1.DataBind();
            }
        }

        protected void dd1_Changed(object sender, EventArgs e)
        {
            dd2.DataSource = Data.GetSource(int.Parse(dd1.SelectedValue));
            dd2.DataTextField = "Text";
            dd2.DataValueField = "Value";
            dd2.DataBind();
        }

        protected void dd2_Changed(object sender, EventArgs e)
        {
            lbl1.Text = dd1.SelectedValue.ToString() + " - " + dd2.SelectedValue.ToString();
        }
    }

    public class Data
    {
        public string Text { get; set; }
        public int Value { get; set; }

        public static List<Data> GetSource(int n)
        {
            List<Data> d = new List<Data>();
            Enumerable.Range(1, n).ToList().ForEach(delegate(int i)
            {
                Data dd = new Data { Text = i.ToString(), Value = i };
                d.Add(dd);
            });
            return d;
        }
    }
}


Hope this helps! Do let me (us) know if you have any questions!
 
Share this answer
 
Comments
day_hard 5-May-11 11:03am    
Really thanks Karthik, you inspired me the solution, i used PreRender event of the second dropdownlist, and worked successfuly, the key was PreRender event

protected void DropDownList2_PreRender(object sender, EventArgs e)
{
Label1.Text = DropDownList2.SelectedValue.ToString();
}
Karthik. A 5-May-11 12:17pm    
no problem, you are welcome!
the key was PreRender event like:

protected void DropDownList2_PreRender(object sender, EventArgs e)
{ 
    Label1.Text = DropDownList2.SelectedValue.ToString(); 
}
 
Share this answer
 
v2
Comments
Monjurul Habib 5-May-11 15:07pm    
edited: added code block.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900