oshirowanen
oshirowanen

Reputation: 15945

Updating GridView with a DropDownList control

I have the following line in my code:

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

But when I run this, I get the following error:

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

Any idea why this might be?


Relevant part of the GridView would be this:

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

Upvotes: 1

Views: 2324

Answers (3)

Prashanth
Prashanth

Reputation: 177

This will do the trick

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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460238

Since your DropDownList most likely is in a TemplateField you can get it's reference via 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;

Upvotes: 2

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

You must use e.Item.FindControl in RowDataBound

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

Upvotes: 1

Related Questions