Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# ASP.NET Web-Development , +
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 ..
.
.
.
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 5-May-11 4:26am
Edited 5-May-11 4:43am
v2
Comments
mksharma38 at 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 at 5-May-11 9:42am
   
u can aslo use DropDownList2.SelectedValue
or DropDownList2.Text
day_hard at 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 at 5-May-11 10:18am
   
I guess you are trying to access DropDownList2 before populating it
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
Comments
Marcus Kramer at 5-May-11 9:44am
   
+5. I think you got it.
day_hard at 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 at 5-May-11 10:05am
   
Is the second drop down populated after you select an item in the first drop down?
day_hard at 5-May-11 10:06am
   
yes indeed, its populated successfuly
Karthik. A at 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.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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:
 
<%@ 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:
 
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!
  Permalink  
Comments
day_hard at 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 at 5-May-11 12:17pm
   
no problem, you are welcome!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

the key was PreRender event like:
 
protected void DropDownList2_PreRender(object sender, EventArgs e)
{ 
    Label1.Text = DropDownList2.SelectedValue.ToString(); 
}
  Permalink  
v2
Comments
Monjurul Habib at 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)

  Print Answers RSS
0 OriginalGriff 520
1 Maciej Los 290
2 Richard MacCutchan 265
3 BillWoodruff 265
4 Suraj Sahoo | Coding Passion 155
0 OriginalGriff 8,764
1 Sergey Alexandrovich Kryukov 7,437
2 DamithSL 5,639
3 Maciej Los 5,279
4 Manas Bhardwaj 4,986


Advertise | Privacy | Mobile
Web01 | 2.8.1411028.1 | Last Updated 5 May 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100