isviewtback中Gridview中的头DDL

时间:2018-04-27 09:13:59

标签: c# asp.net gridview postback rowdatabound

我的gridview中有一个标题DDL,由于某种原因,它不会保留我选择的值,而是将gridview和标题绑定到" 起始位置 "

优先级的DDL标题中,我选择了值' 99'但之后我的标题回到我ListItem的起始位置(即优先级)

enter image description here

enter image description here

    <HeaderTemplate>
<asp:DropDownList ID="ddlPriorityHeader" AutoPostBack="True" AppendDataBoundItems="True" OnSelectedIndexChanged="ddlHeader_SelectedIndexChanged" runat="server">
                                 <asp:ListItem>Priority</asp:ListItem>
                            </asp:DropDownList>
                        </HeaderTemplate>

我有一个RowDatabound用于gridview但是我什么都没做,然后找到标题的DDL然后绑定DDL。

protected void gwActivity_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //.............. some code.....//

 string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(CS))
                {
                    SqlCommand cmd = new SqlCommand("SELECT  DISTINCT [Priority] FROM [BI_Planning].[dbo].[tblPriority]", con);
                    con.Open();
                    ddlPriority.DataSource = cmd.ExecuteReader();
                    ddlPriority.DataTextField = "Priority";
                    ddlPriority.DataBind();
                }

}

我已将gridview放入方法中:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridviewActivity();
    }
} 

我可以每次为我的网格视图绑定我的DDL吗?我被困在这里......

1 个答案:

答案 0 :(得分:1)

您需要将ddlPriority个所选文字存储在ViewState之类的临时位置,以便在回发之间保持价值。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ViewState["PriorityText"] = "Priority";
        BindGridviewActivity();
    }
}

aftrt ddlPriority.DataBind();将选择的文字设置为ViewState

ddlPriority.Items.FindByText(ViewState["PriorityText"].ToString()).Selected = true;

并在ddlHeader_SelectedIndexChanged设置ViewState到所选文字

protected void ddlHeader_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList ddlHeader = (DropDownList)sender;
    ViewState["PriorityText"] = ddlHeader.SelectedItem.Text;
}

查看此complete example了解详情