GridView类容器中的DropDownList联动

-

实例说明:

部门,与部门人员2个下拉框。

(1)前台码

<EditItemTemplate>
部门:

<asp:DropDownList ID="ddlstdepartment" runat="server" OnTextChanged="ddlstdepart_TextChanged" AutoPostBack="True"></asp:DropDownList>
人员:

<asp:dropdownlist ID="ddlstperson" runat="server" AutoPostBack="True" OnTextChanged="ddlstperson_TextChanged"></asp:dropdownlist>

<!--这个literal用于指定编辑模式下默认值选定-->
<asp:Literal ID="luserid" runat="server" Text='<%# Eval("userid") %>' Visible="false"></asp:Literal>
</EditItemTemplate> 

(2)后台码

在DataRowBound事件中进行数据绑定 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
         if ((DropDownList)e.Row.FindControl("ddlstdepartment") != null)
        {
            Literal luserid = e.Row.FindControl("luserid") as Literal; //userid

            DropDownList ddlstdepartment = e.Row.FindControl("ddlstdepartment") as DropDownList;
            BindDepList(ddlstdepartment);//绑定部门
            ddlstdepartment.SelectedValue = myPerson.DepartmentId.ToString();//指定默认选定

            DropDownList ddlstperson = e.Row.FindControl("ddlstperson") as DropDownList;

            BindDepPersonList(ddlstperson, myPerson.DepartmentId);//绑定人员
            ddlstperson.SelectedValue = myPerson.UserId;//指定默认选定
        }
    }

指定部门下拉框为autopostback为true。并注册事件ddlstdepart_TextChanged

事件内容如下:

protected void ddlstdepart_TextChanged(object sender, EventArgs e)
    {
        DropDownList ddlstdepartment = (DropDownList)sender;
        GridViewRow gvr = (GridViewRow)ddlstdepartment.NamingContainer;
        DropDownList ddlstperson = (DropDownList)gvr.FindControl("ddlstperson");
        DataSet ds = new DataSet();
        ds = pp.ShowPersonDs(1, 100, BaseData.enums.eQuestDataType.data, Convert.ToInt32(ddlstdepartment.SelectedItem.Value));

        ddlstperson.DataValueField = "userid";
        ddlstperson.DataTextField = "username";

        ddlstperson.DataSource = ds.Tables[0].DefaultView;
        ddlstperson.DataBind();

        lhidingids.Text = ddlstperson.SelectedItem.Value;//=================(一个页面隐藏Literal,当然也可以用页面状态:ViewState)
    }

这个事件很重要,通过NamingContainer来找到同处于GridView中的两个下拉框(部门,人员),使其产生二级联动(选择部门,人员下拉框自动变化)。

其中注释==============这个部门,很重要。因为编辑模式下需要。

人员下拉框事件ddlstperson_TextChanged

protected void ddlstperson_TextChanged(object sender, EventArgs e)
    {
        DropDownList ddlstperson = (DropDownList)sender;

        lhidingids.Text = ddlstperson.SelectedItem.Value;//================很重要
    }

 (3)编辑模式

bound事件中指定的默认值,在编辑模式下,二级下拉框会出现不能选值的情况。意思是:部门下拉框选项变化,人员下拉框联动,但更新时,不能选定人员下拉框的值,而是默认值,所以不能更新,原因是:在编辑事件中,Bound事件依然执行,所以总是那个默认值。因此需要一个用于存放选定值的状态(ViewState,或带有状态的控件,这里我用Literal)

这样在编辑模式下,更新时,用lhidingids.Text即可。

博客园大道至简

http://www.cnblogs.com/jams742003/

转载请注明:博客园

原文地址:https://www.cnblogs.com/jams742003/p/1459970.html