Manipulating DropDownList within TemplateField
I have a dropdownlist inside of a TemplateField, within a GridView.
I would like to dynamically add list items to it and write code to handle w开发者_如何学Pythonhen the index changes. How do I go about manipulating the list, since I can't directly reference the DropDownList when it's in a TemplateField.
Here is my code:
<asp:TemplateField HeaderText="Transfer Location" Visible="false">
<EditItemTemplate>
<asp:DropDownList ID="ddlTransferLocation" runat="server" ></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
If I'm understanding what you want to do correctly, you can handle adding items to your drop down like this:
foreach (GridViewRow currentRow in gvMyGrid.Rows)
{
DropDownList myDropDown = (currentRow.FindControl("ddlTransferLocation") as DropDownList);
if (myDropDown != null)
{
myDropDown.Items.Add(new ListItem("some text", "a value"));
}
}
Then, if you mean handling the index change of the DropDownList you just need to add an event handler to your control:
<asp:DropDownList ID="ddlTransferLocation" runat="server" OnSelectedIndexChanged="ddlTransferLocation_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
Then in that event handler you can use (sender as DropDownList)
to get whatever you need from it:
protected void ddlTransferLocation_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList myDropDown = (sender as DropDownList);
if (myDropDown != null) // do something
{
}
}
精彩评论