自定义Gridview的表头

    #region 自定义表头

    protected void gvList_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //判断创建的行是不是标题行
        if (e.Row.RowType == DataControlRowType.Header)
        {
            TableCellCollection tcl = e.Row.Cells;
            //清除自动生成的表头
            tcl.Clear();

            //添加新的表头
            tcl.Add(new TableHeaderCell());
            tcl[0].RowSpan = 2;
            tcl[0].Text = "标题1";
            tcl[0].BackColor = (Color)ColorTranslator.FromHtml("#F3F9FF");
            tcl[0].BorderColor = (Color)ColorTranslator.FromHtml("#DAE9FF");

            //Label l1 = new Label();
            //l1.Text = "label";
            //Button bt = new Button();
            //bt.Text = "button";
            ////因为自定义表头,所以原来系统中实现的排序功能就失效了
            ////下面语句可以自己在表头中添加控件,自己实现排序功能
            //tcl[0].Controls.Add(l1);
            //tcl[0].Controls.Add(bt);

            tcl.Add(new TableHeaderCell());
            tcl[1].RowSpan = 2;
            tcl[1].Text = "标题2";
            tcl[1].BackColor = (Color)ColorTranslator.FromHtml("#F3F9FF");
            tcl[1].BorderColor = (Color)ColorTranslator.FromHtml("#DAE9FF");

            tcl.Add(new TableHeaderCell());
            tcl[2].ColumnSpan = 3;
            tcl[2].Text = "标题3";
            tcl[2].BackColor = (Color)ColorTranslator.FromHtml("#FEEFFF");
            tcl[2].BorderColor = (Color)ColorTranslator.FromHtml("#FCDAFF");

            tcl.Add(new TableHeaderCell());
            tcl[3].ColumnSpan = 3;
            tcl[3].Text = "标题4";
            tcl[3].BackColor = (Color)ColorTranslator.FromHtml("#EBFFFD");
            tcl[3].BorderColor = (Color)ColorTranslator.FromHtml("#CDFBF5");

            tcl.Add(new TableHeaderCell());
            tcl[4].ColumnSpan = 3;
            tcl[4].Text = "标题5";
            tcl[4].BackColor = (Color)ColorTranslator.FromHtml("#FBFFD3");
            tcl[4].BorderColor = (Color)ColorTranslator.FromHtml("#F9FFCB");

            tcl.Add(new TableHeaderCell());
            tcl[5].RowSpan = 2;
            tcl[5].Text = "标题6";
            tcl[5].BackColor = (Color)ColorTranslator.FromHtml("#F3F9FF");
            tcl[5].BorderColor = (Color)ColorTranslator.FromHtml("#DAE9FF");

            //这段是重点 其实在生成的html中tcl[6]转化为标题
            //所以依照该原则注入html标签来实现,原理有些类似于SQL注入攻击
            tcl.Add(new TableHeaderCell());
            tcl[6].RowSpan = 2;
            tcl[6].Text = "标题7标题3-1标题3-2标题3-3标题4-1标题4-2标题4-3标题5-1标题5-2标题5-3";
            tcl[6].BackColor = (Color)ColorTranslator.FromHtml("#F3F9FF");
            tcl[6].BorderColor = (Color)ColorTranslator.FromHtml("#DAE9FF");

        }


    }
    #endregion

你可能感兴趣的:(自定义Gridview的表头)