Thursday, 19 February 2015

Bind Dropdownlist in Gridview in Asp.net

Bind Dropdownlist in Gridview in Asp.net:

Code in ASPX
 <html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Bind Dropdownlist  inside gridview</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false" OnRowDataBound="gv_RowDataBound" >
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="CountryId" HeaderText="CountryId" />
<asp:BoundField DataField="CountryName" HeaderText="CountryName" />
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server" Width="100px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>


Code in C#:
 SqlConnection con =new SqlConnection("Data Source=Your Data Source ;Integrated Security=true;Initial Catalog=SampleDB");

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
// This method is used to bind gridview from database
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select  CountryId,CountryName from CountryMaster", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gv.DataSource = ds;
gv.DataBind();

}

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
con.Open();
var ddl = (DropDownList)e.Row.FindControl("ddlCity");
int CountryId = Convert.ToInt32(e.Row.Cells[0].Text);
SqlCommand cmd = new SqlCommand("select * from StateMaster where CountryID=" + CountryId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddl.DataSource = ds;
ddl.DataTextField = "StateName";
ddl.DataValueField = "StateID";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("--Select State--", "0"));
}
}

No comments:

Post a Comment