gridview中的下拉列表,选中的值不会更改

时间:2017-03-16 21:05:49

标签: c# asp.net gridview

这似乎是一个非常简单的问题,但它已经杀了我的一天。 我有一个可更新的gridview,我将一个下拉列表放在其中一列的编辑模式中。 DDL中的项目是静态设置的。但是所选项目始终是第一项。我该如何解决这个问题?

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    string userID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lbluserID")).Text;

    string role = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropDownList1")).SelectedValue;

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = DBSettings.sqlConn;
    cmd.CommandText = "Update tbl_users set role=@role , pending='false' ,approved='true' , declined='false' where ID=@ID";
    cmd.Parameters.AddWithValue("@role", role);
    cmd.Parameters.AddWithValue("@ID", userID);
    cmd.ExecuteNonQuery();
    GridView1.EditIndex = -1;
    gridFill();
}

这里是gridView的aspx(只有ddl部分):

<asp:TemplateField HeaderText="Role">
    <EditItemTemplate>
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
            <asp:ListItem Value="">--Select--</asp:ListItem>
            <asp:ListItem Value="Admin" Text="Admin"></asp:ListItem>
            <asp:ListItem Value="Editor" Text="Editor"></asp:ListItem>
            <asp:ListItem Value="Viewer" Text="Viewer"></asp:ListItem>
        </asp:DropDownList>
    </EditItemTemplate>
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text="pending"></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

1 个答案:

答案 0 :(得分:0)

这没有看到你的GridView数据绑定代码,但我认为你没有在IsPostBack检查中包含dababinding。

if (!Page.IsPostBack)
{
    GridView1.DataSource = yourSource;
    GridView1.DataBind();
}

如果你不这样做,GridView将从头开始重建,DropDownList将被设置为它的默认位置。