Posts tagged: multiple dropdownlist using sqlserver

Aug 31 2009

Multiple DropDownlist Using Asp.net and Database

Step1 : Create category table in your Database (the table creation code is below link

category and subcategory tables

Step2: Create SubCategory table in Your Database

CREATE TABLE [dbo].[tblSubCategory](
[SubCategoryID] [int] IDENTITY(1,1) NOT NULL,
[CategoryID] [int] NOT NULL,
[SubCategory] [varchar](50)  NOT NULL,
CONSTRAINT [PK_tblSubCategory] PRIMARY KEY CLUSTERED
(
[SubCategoryID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Step 3: Enter Below Data into Subcategory table

subcategory

subcategory

step 4: Drag Two Dropdownlist in Default.aspx page

DropDownList1 Property of ID is ddlCategories and AutoPostBack is True //Remember

DropDownList2 Property of ID is ddlSubCategories

Step 5: Write below code in Default.aspx.cs . Write Connection String code above page_load event then it can apply every function in Default.aspx.cs

Sample code:

//Data Source = Your server name or local  sqlserver name

//Data Source=./SQLEXPRESS (for local Sqlserver)

//Data Source = santhu or 192.168.1.34 (for remote servers)

string ConnectionString = “Data Source=santhu;Initial Catalog=DataBaseName;User Id=sa;Password=abc123″;

protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
GetCategories();
}

}

//Filling Categories code

public void GetCategories()
{
SqlConnection objConn = new SqlConnection(ConnectionString);

string query = “select CategoryID,CategoryName from tblCategory”;
SqlCommand objCmd = new SqlCommand(query, objConn);
objCmd.CommandType = CommandType.Text;

DataSet objDs = new DataSet();
SqlDataAdapter objDa = new SqlDataAdapter(objCmd);

objConn.Open();
objDa.Fill(objDs);
objCmd.ExecuteNonQuery();

ddlCategories.DataTextField = “CategoryName”;
ddlCategories.DataValueField = “CategoryID”;

ddlCategories.DataSource = objDs;
ddlCategories.DataBind();

objConn.Close();
}

//Filling SubCategories Code in SelectedIndexChanged

protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
{

//getting CategoryID
long catID = long.Parse(ddlCategories.SelectedItem.Value);

SqlConnection objConn = new SqlConnection(ConnectionString);

string query = “select *from tblsubCategory where CategoryId=”+catID;
SqlCommand objCmd = new SqlCommand(query, objConn);
objCmd.CommandType = CommandType.Text;

DataSet objDs = new DataSet();
SqlDataAdapter objDa = new SqlDataAdapter(objCmd);

objConn.Open();
objDa.Fill(objDs);
objCmd.ExecuteNonQuery();

ddlSubCategories.DataTextField = “SubCategory”;
ddlSubCategories.DataValueField = “SubCategoryID”;

ddlSubCategories.DataSource = objDs;
ddlSubCategories.DataBind();

objConn.Close();
}

Happy Coding….

Alibi3col theme by Themocracy