hello, im just a beginner and need your help...
DROPDOWNLIST1: i have a table say "cat" with columns-id,category and categoryid... i successfully populated its value from the database.
DROPDOWNLIST2: Also have another table called "products" with columns-id,name,categoryid.i need to populate my DROPDOWNLIST2 based on categoryid i retrieve from DROPDOWNLIST1
In my code im getting an error at the below line of code
int id = int.Parse(DropDownList1.SelectedValue.ToString());
here is my code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bindcatdropdown();
}
}
protected void bindcatdropdown()
{
DataTable table = new DataTable();
using (SqlConnection con = new SqlConnection(constr))
{
string sql = "select category,categoryid from cat ORDER BY categoryid";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
}
DropDownList1.DataSource = table;
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable table = new DataTable();
int id = int.Parse(DropDownList1.SelectedValue.ToString());
using (SqlConnection con = new SqlConnection(constr))
{
string sql = "select name,categoryid from products WHERE categoryid=@cid ORDER BY categoryid";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("@cid", id);
da.Fill(table);
}
}
}
DropDownList2.DataSource = table;
DropDownList2.DataBind();
}