Saturday 27 October 2012

bind dropdownlist in gridview in asp.net


In this article I will explain how to bind data to dropdownlist in inside of gridview in asp.net.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>bind dropdownlist in gridview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="Gv_Data" runat="server" AutoGenerateColumns="false"OnRowDataBound="Gv_Data_RowDataBound" >
<Columns>
<asp:BoundField DataField="ProductId" HeaderText="ProductId" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" />
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:DropDownList ID="ddllist" runat="server" Width="100px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

Now add following namespaces in codebehind:



SqlConnection con =new SqlConnection(" Your connection string");


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 * from Products", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
Datatable dt=New Datatable();
da.Fill(dt);
con.Close();
Gv_Data.DataSource = dt;
Gv_Data.DataBind();

}

protected void Gv_Data_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
con.Open();
var ddl = (DropDownList)e.Row.FindControl("ddllist");
int ProductId = Convert.ToInt32(e.Row.Cells[0].Text);
SqlCommand cmd = new SqlCommand("select * from Products where ProductID=" + ProductId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
Datatable dt=New datatable();
da.Fill(dt);
con.Close();
ddl.DataSource = dt;
ddl.DataTextField = "ProductName";
ddl.DataValueField = "ProductID";
ddl.DataBind();
ddl.Items.Insert(0,"Select");
}
}

No comments:

Post a Comment