2014年5月21日 星期三

ASP.NET GridView EditItemTemplate變換不同物件

ASP.NET GridView EditItemTemplate變換不同物件

在RowEditing時依據資料來源顯示不同的物件,下列以TextBox程DropDownList為例:
hfGvnetobject=>存放來自資料庫記載的物件別(TextBox or DropDownList)
hfGvnetobject.Value 等於TextBox時,顯示TextBox隱藏DropDownList物件
hfGvnetobject.Value 等於DropDownList時,顯示DropDownList隱藏TextBox物件
以下範例:

HTML:
<asp:TemplateField HeaderText="value">
    <ItemStyle HorizontalAlign="Center" Width="170" />
    <EditItemTemplate>
        <asp:HiddenField ID="hfGvnetobject" runat="server" Value='<%# Bind("netobject") %>' />
        <asp:TextBox ID="tbxGvvalue1" runat="server" Text='<%# Bind("value1") %>'></asp:TextBox>
        <asp:DropDownList ID="ddlGvvalue1" runat="server"></asp:DropDownList>
    </EditItemTemplate>
    <ItemTemplate>
        <asp:Label ID="lblGvvalue1" runat="server" Text='<%# Eval("value1") %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

C#:
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow) // 非資料行, 離開
            return;
        if (e.Row.RowState == DataControlRowState.Edit || ((int)e.Row.RowState) == 5) //判斷為Edit模式,因偶數列無法判斷故加入((int)e.Row.RowState)==5的條件
        {
            HiddenField hfGvnetobject = e.Row.FindControl("hfGvnetobject") as HiddenField; //取得EditItemTemplate下的hfGvnetobject Value存放物件型態
            TextBox tbxGvvalue1 = e.Row.FindControl("tbxGvvalue1") as TextBox; //取得EditItemTemplate下的TextBox物件
            DropDownList ddlGvvalue1 = (DropDownList)e.Row.FindControl("ddlGvvalue1"); //取得EditItemTemplate下的DropDownList物件
            if (hfGvnetobject.Value == "TextBox") //假設物件型態等於TextBox, 顯示TextBox物件, 隱藏DropDownList物件
            {
                tbxGvvalue1.Visible = true;
                ddlGvvalue1.Visible = false;
            }
            if (hfGvnetobject.Value == "DropDownList") //假設物件型態等於DropDownList, 顯示DropDownList物件, 隱藏TextBox物件
            {
                tbxGvvalue1.Visible = false;
                ddlGvvalue1.Visible = true;
            }
        }
    }

沒有留言:

張貼留言