天天看點

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即可。

部落格園大道至簡

<a href="http://www.cnblogs.com/jams742003/" target="_blank">http://www.cnblogs.com/jams742003/</a>

轉載請注明:部落格園

繼續閱讀