[ASP.NET][WebControl] GridView 自訂樣板編輯

[ASP.NET][WebControl] GridView 自訂樣板編輯

在 GridView 的欄位中進行編輯

使用 TemplateField 設定呈現的樣式

應用 CommandName 的設定在 RowCommand 事件中

撰寫要進行的動作

.aspx 頁面設定



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" DataKeyNames="ProductID" AutoGenerateColumns="False"
            EmptyDataText="沒有資料" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="修改" ShowHeader="False">
                    <ItemTemplate>
                        <asp:ImageButton ID="imgMod" runat="server" CommandName="Mod" ImageUrl="~/Image/V.png"
                            ToolTip="按鈕" CommandArgument='<%# Container.DataItemIndex %>' />
                    </ItemTemplate>
                    <ControlStyle Width="30px" />
                </asp:TemplateField>
                <asp:BoundField DataField="ProductID" HeaderText="商品ID" InsertVisible="False" SortExpression="ProductID"
                    ReadOnly="True" />
                <asp:BoundField DataField="ProductName" HeaderText="商品名稱" SortExpression="ProductName"
                    ReadOnly="True" />
                <asp:BoundField DataField="QuantityPerUnit" HeaderText="單位" ReadOnly="True" SortExpression="QuantityPerUnit" />
                <asp:TemplateField HeaderText="庫存量" SortExpression="UnitsInStock">
                    <ItemTemplate>
                        <asp:Label ID="lb_UnitsInStock" runat="server" Text='<%# Eval("UnitsInStock") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="tb_UnitsInStock" runat="server" Text='<%# Eval("UnitsInStock") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="單價" SortExpression="UnitPrice">
                    <ItemTemplate>
                        <asp:Label ID="lb_UnitPrice" runat="server" Text='<%# Eval("UnitPrice") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="tb_UnitPrice" runat="server" ClientIDMode="Static" Text='<%# Eval("UnitPrice") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField ShowHeader="False">
                    <EditItemTemplate>
                        <asp:Button ID="btnOk" runat="server" OnClick="btnOk_Click" Text="確定" />
                        <asp:Button ID="btnCel" runat="server" OnClick="btnCel_Click" Text="取消" />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

.cs 內容


    {
        if (!IsPostBack)
        {
            GVBind();
        }
    }

    //取得資料
    protected void GVBind()
    {
        using (IDbConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
        {
            string str = "SELECT TOP 10 ProductID,ProductName,QuantityPerUnit,UnitsInStock,UnitPrice from Products";
            using (DbDataAdapter da = new SqlDataAdapter(str, conn.ConnectionString))
            {
                DataTable dt = new DataTable();
                da.Fill(dt);
                GridView1.DataSource = dt;
                GridView1.DataBind();
                dt.Dispose();
            }
        }
    }

    //資料連結 回傳 DataTable
    private DataTable GetDTConn(string str)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(str, conn))
            {
                DataTable oDataTable = new DataTable();
                da.Fill(oDataTable);
                return oDataTable;
            }
        }
    }

    private int CmdSQL(string str,  SqlParameter[] sp)
    {
        try
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
            conn.Open();
            SqlCommand cmd = new SqlCommand(str, conn);
            cmd.Parameters.AddRange(sp);
            return cmd.ExecuteNonQuery();
            //SqlDataReader oDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            //return oDataReader;
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int intRow = (e.CommandArgument.ToString() != "") ? Convert.ToInt32(e.CommandArgument): -1;
        switch (e.CommandName.ToString())
        {
            case "Mod":
                GridView1.EditIndex = intRow;
                GVBind();
                break;
            default:
                break;
        }
    }

    protected void btnOk_Click(object sender, EventArgs e)
    {
        string getsql = "select a.name,a.Length,b.name as type,'' as value " +
            "from syscolumns as a LEFT JOIN dbo.systypes as b ON a.xusertype = b.xusertype " +
            "where id=object_id('Products')"; 
        int intUp = GridView1.EditIndex;
        string strProductID = "";
        string strUnitsInStock = "";
        string strUnitPrice = "";
        if (intUp >=  0)
        {
            DataTable tmpDT = GetDTConn(getsql);    //取得資料表的欄位名稱,格式,長度,值
            strProductID = GridView1.Rows[intUp].Cells[1].Text;
            strUnitsInStock= ((TextBox)this.GridView1.Rows[intUp].FindControl("tb_UnitsInStock")).Text.Trim();
            strUnitPrice =((TextBox)this.GridView1.Rows[intUp].FindControl("tb_UnitPrice")).Text.Trim();
            foreach (DataRow dr in tmpDT.Rows)      //將修改值填入
            {
                switch (dr["name"].ToString())
                {
                    case null:
                    case "":
                        dr["value"] = "Null";
                        break;
                    case "UnitsInStock":
                        dr["value"] = strUnitsInStock;
                        break;
                    case "UnitPrice":
                        dr["value"] = strUnitPrice;
                        break;
                }
            }

            SqlParameter[] spsql = new SqlParameter[tmpDT.Rows.Count];
            StringBuilder sbSql = new StringBuilder("UPDATE Products SET ");
            int sqlindex = 0;
            foreach (DataRow dr in tmpDT.Rows)
            {
                //int index = tmpDT.Rows.IndexOf(dr);   //取得 dr 在 tmpDT 中的 index
                if (dr["value"] != System.DBNull.Value && dr["value"].ToString() != "")
                {
                    sbSql = (sqlindex == 0) ? sbSql.Append(dr["name"] + "=@" + dr["name"]) : sbSql.Append(", " + dr["name"] + "=@" + dr["name"]);
                    spsql[sqlindex] = (dr["value"].ToString() == "Null") ? new SqlParameter("@" + dr["name"], DBNull.Value) : new SqlParameter("@" + dr["name"], dr["value"]);
                    sqlindex ++;
                }
            }
            sbSql.Append(" WHERE ProductID='" + strProductID + "'");
            //變更陣列大小
            Array.Resize(ref spsql, sqlindex);
            CmdSQL(sbSql.ToString(), spsql);
            GridView1.EditIndex = -1;
            GVBind();    
        }
    }

    protected void btnCel_Click(object sender, EventArgs e)
    {
        GridView1.EditIndex = -1;
        GVBind();
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex > -1)
        {
            e.Row.Attributes.Add("onmouseover", "gvcolor=this.style.backgroundColor;this.style.backgroundColor='#e0e0ff'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=gvcolor;");
        }
    }

呈現畫面:

image

image

image

範例檔案 下載

 

Dotblogs 的標籤: ,,