2012年5月22日 星期二

Webform's GridView使用DropDownList時, 如何不用隱藏欄位來傳遞原值呢?

ASP的程式片段


                       <asp:TemplateField HeaderText="業務組">
                            <ItemTemplate>
                                <asp:Label ID="Lab_Department" runat="server" Text='<%# Eval("Department") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="ddl_Department2" runat="server" Width="10em"></asp:DropDownList>
                            </EditItemTemplate>
                            <ItemStyle HorizontalAlign="Left" Wrap="False" />
                        </asp:TemplateField>

asp.cs的程式片段

1.先定義Class變數
string Group;


2.在GridView CaseLists的RowEditing的事件中把ItemTemplate中的原值存到Group.
        protected void CaseLists_RowEditing(object sender, GridViewEditEventArgs e)
        {
            CaseLists.EditIndex = e.NewEditIndex;
            Group = ((Label)CaseLists.Rows[e.NewEditIndex].FindControl("Lab_Department")).Text.Trim();
            BindOrder2();
        }

3.將SelectedValue設為Group即可
        protected void CaseLists_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)//判定当前的行是否属于datarow类型的行
            {
                if ((e.Row.RowState & DataControlRowState.Edit) != 0)
                {
                    if (e.Row.FindControl("ddl_Department2") != null)
                    { 

                        //綁定業務組下拉選單
                        ((DropDownList)e.Row.FindControl("ddl_Department2")).DataSource = CreateDataTable();
                        ((DropDownList)e.Row.FindControl("ddl_Department2")).DataTextField = "Items";
                        ((DropDownList)e.Row.FindControl("ddl_Department2")).DataValueField = "Items";
                        ((DropDownList)e.Row.FindControl("ddl_Department2")).SelectedValue = Group;
                        ((DropDownList)e.Row.FindControl("ddl_Department2")).DataBind();                   
                    }
                }
....}}

沒有留言:

張貼留言