Reputation: 631
I have a dropdown inside the gridview template field.
<asp:templatefield headertext="Bill Period">
<itemtemplate>
<asp:dropdownlist runat="server" id="cboBillPeriod"></asp:dropdownlist>
</itemtemplate>
</asp:templatefield>
I want to populate the dropdown i could i do it? can any please help me.
Upvotes: 2
Views: 16584
Reputation: 33
You can use this for your dropdown in your gridview.
<asp:TemplateField HeaderText="Item Condition" HeaderStyle-Width="80px" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="40px>
<ItemTemplate>
<asp:DropDownList ID="ddlConditions" runat="server" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Under your grid "RowDataBound" event, you will bind your dropdown in code behind using dropdown id.
DropDownList ddlConditions2 = (e.Row.FindControl("ddlConditions") as DropDownList);
DataTable dt = _reader.GetDataTableByCommandFromStoredProc("getYourDropdownData");
ddlConditions2.DataSource = dt;
ddlConditions2.DataTextField = "ConditionName";
ddlConditions2.DataValueField = "Id";
ddlConditions2.DataBind();
ddlConditions2.Items.Insert(0, new ListItem("--Select--", "0"));
Upvotes: 1
Reputation: 17194
You could bind the dropdown in OnRowDataBound
event of GridView as follow:
GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<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>
Code Behind:
With the help of FindControl
method you will be able to get the dropdown control and then you could play with that control.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = GetData("SELECT DISTINCT Country FROM Customers");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Please select"));
// Select the Country of Customer in DropDownList
string country = (e.Row.FindControl("lblCountry") as Label).Text;
ddlCountries.Items.FindByValue(country).Selected = true;
}
}
Upvotes: 4