65.9K
CodeProject 正在变化。 阅读更多。
Home

带有自定义分页器、复选框列、序列号列和自定义导航的自定义 Gridveiw 控件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (6投票s)

2010 年 4 月 7 日

CPOL

3分钟阅读

viewsIcon

54120

downloadIcon

2874

本文包含具有附加功能的自定义 Gridview 控件,例如自定义分页导航控件、带下拉列表的自定义页面大小、复选框列、序列号列

引言

在使用网站时,Grid-view 被证明是一种非常有效、强大且丰富的工具。 它可以帮助我们以分页方式查看数据。 它在大多数时候帮助我们开发网站,但仍然有一些情况下我们需要添加一些功能来满足需求。 例如,添加复选框列(以及编写 JavaScript 代码)、显示序列号、显示页面摘要、动态增加或减少页面大小等。 在本文中,我将创建一个自定义 grid-view 控件,它将在这方面帮助我们。

GVCustomPager02.JPG

如何创建控件

此控件背后的想法非常简单

  • 重写 InitializePager 方法以自定义 gridview
  • 创建一个带有三个单元格的临时表,宽度为 100%
  • 在第一个单元格中,创建导航控件(用于第一页、下一页、上一页、最后一页的图像按钮,用于显示页面计数的 DropdownList
    • 创建 4 个带有 ImageUrl 属性的图像按钮,以便我们可以为导航设置自定义图像
    • 对于图像按钮,为第一页、下一页、上一页、最后一页设置正确的命令参数,即(第一页的页面索引为 0,下一页的页面索引为当前页面索引 +1,上一页按钮的页面索引为当前索引 +1,最后一页的页面索引为页面计数+1)
    • imagebuttonDropdownlist 的点击添加新的事件处理程序,并将 CommandargumentDropdownValue 作为参数传递给 gridviewpageindex 更改事件。
  • 在第二个单元格中,我们在标签中显示 Grid 信息。
  • 在第三个单元格中,我们创建一个带有自定义页面大小的 dropdown 列表,将 eventhandler 附加到所选索引更改并设置 pagesize
  • 创建 Checkbox 列和序列号列
    • 重写 OnRowCreated 方法
    • 检查创建的行是 Header 还是 datarow
    • 检查是否将 CheckboxColumn SerialNoColumn 属性设置为 true
    • 如果为 true,则在 Header 行中首先写入 Check Box 的 Header,然后写入 Serial
    • 如果它是 datarow,则创建 RowLevelCheckboxes
  • 创建 On OnLoad 方法,包括来自 DLL 的 JavaScript 文件
  • 在 Render 上,创建用于选择全部和不选的顶部和底部按钮
GVCustomPager01.JPG

Using the Code

我将在这里解释 Check box 列的大部分代码,我使用了 Scott Mitchel 编写的 JavaScript 代码。 非常感谢这位天才。

自定义 Gridview 控件的属性

属性 类型 目的
CustomPageing 布尔值 启用/禁用自定义分页
CheckBoxColumn 布尔值 启用/禁用 CheckBox
SerialNo 布尔值 启用/禁用序列号列
FirstImage 字符串 设置/获取到 First Navigation Button 的图像路径
NextImage 字符串 设置/获取到 Next Navigation Button 的图像路径
PreviousImage 字符串 设置/获取到 Previous Navigation Button 的图像路径
LastImage 字符串 设置/获取到 Last Navigation Button 的图像路径

设置属性

启用/禁用自定义分页

 public bool CustomPageing
        {
            get { return _CustomPageing; }
            set { _CustomPageing = value; }
        } 

启用/禁用 CheckBox 列

public bool CheckBoxColumn
        {
            get
            {
                return _checkboxColumn;
            }
            set
            {
                _checkboxColumn = value;
                //if Checkbox column is required, then Add New Boundfield 
                //into the gridview row at index 0.
                if (CheckBoxColumn)
                {
                    this.Columns.Insert(0, new BoundField());
                }
            }
        }

启用/禁用序列号列

public bool SerialNoColumn
        {
            get
            {
                return _SrNoColumn;
            }
            set
            {
                _SrNoColumn = value;
                //if SerialNoColumn is required, then Add New Boundfield 
                //into the gridview row at index 0.
                if (SerialNoColumn)
                {
                    this.Columns.Insert(0, new BoundField());
                }
            }
        }

设置/获取到 First Navigation Button 的图像路径

   public string FirstImage
        {
            get { return _nav_first; }
            set { _nav_first = value; }
        }

图像按钮的其他属性是相同的,所以我避免了重复。

InitializePager 事件

在此事件中,我们创建一个带有 3 个单元格的表,用于页面导航、页面摘要和页面大小控件,附加事件处理程序并将此表添加到分页行中

protected override void InitializePager(GridViewRow row, 
		int columnSpan, PagedDataSource pagedDataSource)
        {
            //Checking the type of pager Custom or Default.
            if (!CustomPageing)
            {
                //The pager will be initialized to default. 
                //if we don't want it in the usual way
                base.InitializePager(row, columnSpan, pagedDataSource);
            }
            else
            {
                //Custom Pager

                //Each time we add 1 to columnSpan when properties for 
                //CheckBoxColumn and SerialNoColumn are set to true
                if (CheckBoxColumn) { columnSpan += 1; }
                if (SerialNoColumn) { columnSpan += 1; }

                //Creating Controls
                //Creating DropdownList to Show No of pages in the GridView. 
                DropDownList ddl = new DropDownList();
                ddl.AutoPostBack = true;
                for (int i = 0; i < PageCount; i++)
                {
                    ddl.Items.Add(new ListItem(Convert.ToString(i + 1), i.ToString()));
                }
                //We have to new Add Eventhandler to change page 
                //index on selecting Page number from the Gridview
                ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
                ddl.SelectedIndex = PageIndex;

                //Creating DropdownList having Page size 
                DropDownList ddlPageSize = new DropDownList();
                ddlPageSize.ID = "PageSize";
                ddlPageSize.AutoPostBack = true;
                ddlPageSize.Items.Add(new ListItem("- Page Size -", "10"));
                ddlPageSize.Items.Add(new ListItem("10", "10"));
                ddlPageSize.Items.Add(new ListItem("25", "25"));
                ddlPageSize.Items.Add(new ListItem("50", "50"));
                ddlPageSize.Items.Add(new ListItem("100", "100"));
                ddlPageSize.Items.Add(new ListItem("All", 
			(this.PageCount * this.PageSize).ToString()));
                //add Event Handler to it
                ddlPageSize.SelectedIndexChanged += 
			new EventHandler(ddlPageSize_SelectedIndexChanged);

                //Creating Image Buttons for navigation and setting its page index, 
                //attach eventhandlers for Click
                ImageButton first = new ImageButton();
                first.AlternateText = "|<< First ";

                //If we do not give image or left blank then 
                //it will automatically assign default image.
                first.ImageUrl = (FirstImage == string.Empty) ? 
			Page.ClientScript.GetWebResourceUrl(typeof(InderGrid), 
			"Indrajeet.Web.UI.WebControls.First.gif") : FirstImage;

                //Fist button always has Page index 0 
                first.CommandArgument = "0";
                first.Enabled = PageIndex > 0;
                first.Click += new ImageClickEventHandler(navigate_Click);

                ImageButton prev = new ImageButton();
                prev.AlternateText = " < Prev ";
                prev.ImageUrl = (PreviousImage == string.Empty) ? 
			Page.ClientScript.GetWebResourceUrl(typeof(InderGrid), 
			"Indrajeet.Web.UI.WebControls.Prev.gif") : PreviousImage;

                //Previous button always has Page Index=  Page index -1  
                prev.CommandArgument = string.Format("{0}", (PageIndex - 1));
                prev.Enabled = (PageIndex > 0);
                prev.Click += new ImageClickEventHandler(navigate_Click);

                ImageButton next = new ImageButton();
                next.AlternateText = "Next > ";
                next.ImageUrl = (NextImage == string.Empty) ? 
			Page.ClientScript.GetWebResourceUrl(typeof(InderGrid), 
			"Indrajeet.Web.UI.WebControls.Next.gif") : NextImage;

                //Previous button always has Page Index=  Page index +1  
                next.CommandArgument = string.Format("{0}", (PageIndex + 1));
                next.Enabled = (PageIndex < (PageCount - 1));
                next.Click += new ImageClickEventHandler(navigate_Click);

                ImageButton last = new ImageButton();
                last.AlternateText = "Last >>|";
                last.ImageUrl = (LastImage == string.Empty) ? 
			Page.ClientScript.GetWebResourceUrl(typeof(InderGrid), 
			"Indrajeet.Web.UI.WebControls.Last.gif") : LastImage;
                //Last Button always has Last Page index so it is Page count -1 
                last.CommandArgument = string.Format("{0}", (PageCount - 1));
                last.Enabled = (PageIndex < (PageCount - 1));
                last.Click += new ImageClickEventHandler(navigate_Click);

                //New Creating Table with Tree Cells. 
                //First Cell contains Paging Navigation Control 
                //i.e. First, Next, DropDown for Current Page and Next, Last Record
                //Second Cell contains Paging Summary. 
                //Third Cell will contain The Page Size.

                //Crate a Table Cell One and Add Navigation Controls to it.
                TableCell CellOne = new TableCell();
                CellOne.Controls.Add(first);
                CellOne.Controls.Add(prev);
                CellOne.Controls.Add(PageOf());
                CellOne.Controls.Add(ddl);
                CellOne.Controls.Add(PageTotal());
                CellOne.Controls.Add(next);
                CellOne.Controls.Add(last);

                //Create Cell Two
                TableCell cellTwo = new TableCell();
                cellTwo.Controls.Add(PageInfo(pagedDataSource.DataSourceCount));

                //
                TableCell cellThree = new TableCell();
                cellThree.Controls.Add(ddlPageSize);

                //Create Table and row and add cells in to that Row.
                Table PagerTable = new Table();
                PagerTable.BorderWidth = 0;
                PagerTable.Width = Unit.Percentage(100);
                PagerTable.Rows.Add(new TableRow());
                PagerTable.Rows[0].Cells.Add(CellOne);
                PagerTable.Rows[0].Cells.Add(cellTwo);
                PagerTable.Rows[0].Cells.Add(cellThree);
                PagerTable.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Left;
                PagerTable.Rows[0].Cells[1].HorizontalAlign = HorizontalAlign.Center;
                PagerTable.Rows[0].Cells[2].HorizontalAlign = HorizontalAlign.Right;

                //Now Add this table to GridViewRow
                row.Controls.AddAt(0, new TableCell());
                row.Cells[0].ColumnSpan = columnSpan;
                row.Cells[0].Controls.AddAt(0, PagerTable);
            }
        }

GridView 的 OnRowCreated 事件

在此事件中,如果需要,我们在每一行添加 CheckBoxColumn SerialNoColumn

 protected override void OnRowCreated(GridViewRowEventArgs e)
        {
            //Checking Rowtype 
            if (e.Row.RowType != DataControlRowType.Pager)
            {
                //Add header Columns for Checkbox and Serial No
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    //Render Checkbox control if CheckBoxColumn is true
                    if (CheckBoxColumn)
                    {
                        HtmlInputCheckBox chkheader = new HtmlInputCheckBox();
                        chkheader.ID = "HeaderLevelCheckBox";
                        chkheader.Attributes.Add("onclick", 
			"ChangeAllCheckBoxStates(this.checked);");
                        e.Row.Cells[0].Controls.Add(chkheader);
                        _ArrayValues = new List<string>();
                        _ArrayValues.Add(string.Concat("'", chkheader.ClientID, "'"));
                    }
                    //Render Serial Number Column if SerialNoColumn is true
                    if (SerialNoColumn)
                    {
                       
                        Label lbl = new Label();
                        lbl.ID = "SrNo" + e.Row.DataItemIndex + 1;
                        lbl.Text = "Srial No.";
                        //Checkbox column is set to first so check if,
                        //checkboxColumn is present then SerialNoColumn 
                        //will be second else first
                        e.Row.Cells[(CheckBoxColumn) ? 1 : 0].Controls.Add(lbl);
                    }
                }
                //Add DataRows for checkbox and SerialNoColumn
                else if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    if (CheckBoxColumn)
                    {
                        HtmlInputCheckBox chkRow = new HtmlInputCheckBox();
                        chkRow.ID = "RowLevelCheckBox" + i++;
                        chkRow.Attributes.Add("onclick", "ChangeHeaderAsNeeded();");
                        e.Row.Cells[0].Controls.Add(chkRow);
                        _ArrayValues.Add(string.Concat("'", chkRow.ClientID, "'"));
                    }
                    if (SerialNoColumn)
                    {
                        Label lbl = new Label();
                        lbl.ID = "SrNo" + e.Row.DataItemIndex + 1;
                        lbl.Text = (e.Row.DataItemIndex + 1).ToString(); ;
                        e.Row.Cells[(CheckBoxColumn) ? 1 : 0].Controls.Add(lbl);
                    }
                }
            }

            base.OnRowCreated(e); 
       }

Button/DropDownList 事件处理程序

protected virtual void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            OnPageIndexChanging(new GridViewPageEventArgs
		(Convert.ToInt16(((DropDownList)sender).SelectedValue)));
        }

        //For Pagesize set pagesize to DropDownLists SelectedValue and 
        //raise GridView's OnPageIndexChanging method and pass currentpage index to it
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.PageSize = Convert.ToInt16(((DropDownList)sender).SelectedValue);
            OnPageIndexChanging(new GridViewPageEventArgs(this.PageIndex));
        }

        //On Click Event of Navigation Button
        //we have to pass CommandArgument as argument
        //to GridView's OnPageIndexChanging method
        protected virtual void navigate_Click(object sender, EventArgs e)
        {
            OnPageIndexChanging(new GridViewPageEventArgs
		(int.Parse(((ImageButton)sender).CommandArgument)));
        }

其他页面信息控件

private Label PageOf()
        {
            Label lbl = new Label();
            lbl.Text = "Page ";
            return lbl;
        }

        //For showing GridView's Page Count
        private Label PageTotal()
        {
            Label lbl = new Label();
            lbl.Text = string.Format(" of {0}", PageCount);
            return lbl;
        }

        //For Displaying Current Record
        private Label PageInfo(int rowCount)
        {
            Label lbl = new Label();
            int FirstRowCurrentPage = ((PageIndex * PageSize) + 1);
            int LastRowCurrentPage = 0;
            int LastPageIndicator = rowCount % PageSize;
            LastRowCurrentPage = (PageCount == PageIndex + 1) ? 
		(FirstRowCurrentPage + LastPageIndicator - 1) : 
		(FirstRowCurrentPage + PageSize - 1);
            lbl.Text = String.Format("Record {0} to {1} of {2}", 
		FirstRowCurrentPage, LastRowCurrentPage, rowCount);
            return lbl;
        }

On Load 事件

protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //Calling Javascript file
            string gridScriptPath = Page.ClientScript.GetWebResourceUrl
			(this.GetType(), _gridCheck_JS);
            if (!Page.ClientScript.IsClientScriptIncludeRegistered
			(this.GetType(), _gridCheck_JS))
                Page.ClientScript.RegisterClientScriptInclude
			(this.GetType(), _gridCheck_JS, gridScriptPath);
        }

On Render 事件

protected override void Render(HtmlTextWriter writer)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            if (Rows.Count > 0)
            {
                HtmlInputButton btn = new HtmlInputButton();
                btn.ID = "SelectAllU";
                btn.Value = "Select All";
                btn.Attributes.Add("onclick", "ChangeAllCheckBoxStates(true);");

                HtmlInputButton btn2 = new HtmlInputButton();
                btn2.ID = "SelectNoneU";
                btn2.Value = "Select None";
                btn2.Attributes.Add("onclick", "ChangeAllCheckBoxStates(false);");

                HtmlInputButton btn3 = new HtmlInputButton();
                btn3.ID = "SelectAllD";
                btn3.Value = "Select All";
                btn3.Attributes.Add("onclick", "ChangeAllCheckBoxStates(true);");

                HtmlInputButton btn4 = new HtmlInputButton();
                btn4.ID = "SelectNoneD";
                btn4.Value = "Select None";
                btn4.Attributes.Add("onclick", "ChangeAllCheckBoxStates(false);");

                btn.RenderControl(writer);
                btn2.RenderControl(writer);
                base.Render(writer);
                btn3.RenderControl(writer);
                btn4.RenderControl(writer);
            }
            else
            {
                base.Render(writer);
            }
            if (CheckBoxColumn)
            {
                //Creating Javascript Array of Gridview Checkbox 
                Literal CheckBoxIDsArray = new Literal();
                CheckBoxIDsArray.Text = "<script type="\"text/javascript\"">\n\n" + 
		string.Concat("var CheckBoxIDs =  new Array(", string.Join
		(",", _ArrayValues.ToArray()), ");") + "\n\n</script>";
                CheckBoxIDsArray.RenderControl(writer);
                writer.RenderEndTag();
            }

        }

特别感谢

Scott Mitchell 用于 Checkbox 列 JavaScript 代码
© . All rights reserved.