Default.aspx
// i have a two drop down inside gridview fst one for country seccond for state
//on load binding country ddl to country list and state dropdownlist to state list
//on fst ddl click i am binding it to state
//on state drop down click i am binding its country to fst ddl
<asp:GridView ID="grd" runat="server" AutoGenerateColumns="False"
onrowdatabound="grd_RowDataBound"
<Columns>
<asp:TemplateField HeaderText="Country">
<ItemTemplate >
<asp:DropDownList ID="DropDownList1" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" Width="200px" AutoPostBack="true" EnableViewState="true" runat="server" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" Width="200px" AutoPostBack="true" EnableViewState="true" runat="server" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Default.cs
// i am using edmx to bind DropDown in grid
protected void DropDownList1_SelectedIndexChanged(object sen, EventArgs e)
{
if (Page.IsPostBack)
{
var ddl = (DropDownList)sen;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
DropDownList ddl2 = (DropDownList)row.FindControl("DropDownList2");
int idx = row.RowIndex;
if (ddl.SelectedIndex > 0)
{
ddl2.Items.Clear();
var x = ddl.SelectedValue;
int id = Convert.ToInt32(x);
TestEntities en = new TestEntities();
ddl2.DataSource = en.State.Where(s => s.Country.CountryID == id).ToList();
ddl2.DataTextField = "StateName";
ddl2.DataValueField = "StateID";
ddl2.DataBind();
ddl2.Items.Insert(0, new ListItem("--Select State --", "0"));
}
}
}
protected void DropDownList2_SelectedIndexChanged(object sen, EventArgs e)
{
if (Page.IsPostBack)
{
var ddl2 = (DropDownList)sen;
GridViewRow row = (GridViewRow)ddl2.Parent.Parent;
DropDownList ddl1 = (DropDownList)row.FindControl("DropDownList1");
int idx = row.RowIndex;
if (ddl2.SelectedIndex > 0)
{
ddl1.Items.Clear();
var x = ddl2.SelectedValue;
int id = Convert.ToInt32(x);
TestEntities en = new TestEntities();
var contryId= en.State.Where(s => s.StateID == id).First();
int cc = Convert.ToInt32(contryId.CountryReference.EntityKey.EntityKeyValues[0].Value);
ddl1.DataSource = en.Country.Where(s => s.CountryID ==cc ).ToList();
ddl1.DataTextField = "CountryName";
ddl1.DataValueField = "CountryID";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("--Select Country --", "0"));
}
}
}
happy coding :) :) :)