1

我的代码中有以下行:

cmd.Parameters.Add("@priority", SqlDbType.VarChar).Value = ((DropDownList)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).SelectedValue;

但是当我运行它时,我收到以下错误:

Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.DropDownList'.

知道为什么会这样吗?


GridView 的相关部分是这样的:

<asp:TemplateField HeaderText="Priority">
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# Bind("priority") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:DropDownList ID="DropDownList1" runat="server" 
            SelectedValue='<%# Bind("priority") %>'>
            <asp:ListItem Value="0">Low</asp:ListItem>
            <asp:ListItem Value="1">Normal</asp:ListItem>
            <asp:ListItem Value="2">High</asp:ListItem>
        </asp:DropDownList>
    </EditItemTemplate>
</asp:TemplateField>
4

3 回答 3

2

由于您DropDownList最有可能在 a 中TemplateField,因此您可以通过以下方式获得它的参考FindControl("ID")

public void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridView gv = (GridView)sender;
    GridViewRow row = gv.Rows[e.RowIndex];
    // assuming its ID is "DropDownList1"
    DropDownList ddl = (DropDownList)row.FindControl("DropDownList1"); 
    String selectedValue = ddl.SelectedValue;
于 2012-09-03T12:46:03.607 回答
1

您必须e.Item.FindControl在 RowDataBound 中使用

var ddl = (DropDownList) e.Item.FindControl("YourId");
var value = ddl.SelectedValue;
于 2012-09-03T12:44:30.377 回答
0

这会成功的

public void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    string spacediv3 = ((DropDownList)gridviewname.Rows[e.RowIndex].Cells[location].FindControl("dropdownlit1")).SelectedItem.ToString();
}
于 2012-09-03T15:13:05.880 回答