2012-09-03 29 views
1

我在下面的一行代碼:更新的GridView有DropDownList控件

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> 
+0

你能告訴我們電網的ASPX標記? –

+0

使用'FindControl(「DropdownID」)'方法。 – adatapost

+0

@TimSchmelter,更新了GridView相關部分的問題。 – oshirowanen

回答

2

由於您DropDownList最有可能是在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; 
1

您必須的RowDataBound

使用 e.Item.FindControl
var ddl = (DropDownList) e.Item.FindControl("YourId"); 
var value = ddl.SelectedValue; 
0

這將這樣的伎倆

public void gv_RowUpdating(object sender, GridViewUpdateEventArgs e) 
{ 
    string spacediv3 = ((DropDownList)gridviewname.Rows[e.RowIndex].Cells[location].FindControl("dropdownlit1")).SelectedItem.ToString(); 
} 
+0

這是另一種方法,但這不是推薦的方法。 – Prashanth

相關問題