HTML Markup
The HTML Markup contains an ASP.Net GridView with DropDownList in ItemTemplate of TemplateField.
<asp:gridview id="GridView1" runat="server" autogeneratecolumns="false" onrowdatabound="OnRowDataBound" xmlns:asp="#unknown">
<columns>
<asp:boundfield headertext="Name" datafield="ContactName" />
<asp:templatefield headertext="Country">
<itemtemplate>
<asp:label id="lblCountry" runat="server" text="<%# Eval("Country") %>" visible="false" />
<asp:dropdownlist id="ddlCountries" runat="server">
</asp:dropdownlist>
</itemtemplate>
</asp:templatefield>
</columns>
</asp:gridview>
Binding the GridView
The below code binds the ASP.Net GridView with records from the Customers table of the Northwind database using C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData("SELECT ContactName, Country FROM Customers");
GridView1.DataBind();
}
}
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = GetData("SELECT DISTINCT Country FROM Customers");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
ddlCountries.Items.Insert(0, new ListItem("Please select"));
string country = (e.Row.FindControl("lblCountry") as Label).Text;
ddlCountries.Items.FindByValue(country).Selected = true;
}
}