实现了选择、跳页、排序、导出EXCEL等功能的自定义DataGrid(原码)
引子:
最近公司行政服务中心要我做一个系统,做系统期间又用到了哪个让人觉得说简单又复杂DataGrid控件。记得公司花费不少向深信通购买了一组自定义控件,其中一个就是实现了跳页、排序、导出EXCEL等功能的DataGrid,所以萌发了自己开发一个自定义控件的念想。
一、感谢:
吃水不忘挖井人,其实我实现的这些功能都是网上无私“传道授业”的大侠们已经实现了的,我只不过把他们各自实现的功能综合了一下,有些修改了一些没有完善的地方。如下是我参考的文章:
1、爱问天
http://www.webyi.com/wschool/program/aspnet/20080606/5802.html
扩展GridView控件实现多选 - 网翼.mht
2、椰子林
CSDN技术中心 ASP_NET中自定义控件的创建和使用
http://dev.csdn.net/article/29/29799.shtm
http://blog.csdn.net/lizanhong
3、DarkAngel的思维空间
一个带自定义分页,排序功能的DATAGRID控件(公开源码)
http://www.cnblogs.com/DarkAngel/archive/2005/07/12/191138.html
二、使用提示:
将生成的DLL添加进选项卡,使用的时候一定要把绑定数据的函数放在(!IsPostBack)外面,即:不管什么情况下,执行Page_Load时都要进行数据绑定,不然会出现引用不到对象的情况。不知道哪位大侠看过原码以后有什么解决方法没有。
介绍:
先看效果图:
(机子上没有截图软件,不是很清楚,抱歉)
功能介绍:
1、选择记录:点击某一行的任意记录,实现该行的选择,点击标题的选择框,实现全选。在后台使用CreateSelectedRowItems()函数取得选择后的行。(这个忘了测试不知道是否能成功)
2、排序:只要给DataGrid加上数据绑定,即可实现,都知道是怎么回事的,拿到自己的程序一试就知道
3、设置每页的记录数:不要尝试输入非整数,会判断的,点击确定。
4、上下翻页:
5、跳页:在下拉框里面选择需要的页码后,自动跳到对应的页码。
6、导出EXCEL,实际上是导出为文本,只不过在EXCEL打开后是可以自动分列,类似于CSV。不做EXCEL格式的是觉得耗费太大,用处不大。实际使用中,数据都比较多,而网络传输都比较慢。能倒出来就可以了。自己加工一下。
以下是原码,不懂的跟问吧,有空会上来解答的。
using System;
using System.Data;
using System.ComponentModel;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using System.Web.Configuration;
using System.Drawing;
using System.IO;
namespace test
{
/// <summary>
/// WebBarDataGrid 的摘要说明
/// </summary>
public class WebBarDataGrid : DataGrid
{
private HtmlInputCheckBox cb; //各行前面的多选框
private Button HideButton = new Button();//隐藏按钮用于引发事件,后面会说到
DropDownList Ddl = new DropDownList();
DataView dv = new DataView();
Label PnSizeLab = new Label();
Label footLabel1 =new Label() ;
Label footLabel2 =new Label();
TextBox footTextBox1= new TextBox() ;
Label eventFlg = new Label();
Button btn = new Button();
Label jumpLabel1 = new Label();
Label jumpLabel2 = new Label();
LinkButton btnnext = new LinkButton();
LinkButton btnprev = new LinkButton();
private int countflg=0;
LinkButton excebtn = new LinkButton();
string[] HeaderText;
public Color SingleBackGroundColor
{
get
{
return ViewState["SingleBackGroundColor"] != null ? (Color)ViewState["SingleBackGroundColor"] : Color.Empty;
}
set
{
ViewState["SingleBackGroundColor"] = value;
}
}
public Color DoubleBackGroundColor
{
get
{
return ViewState["DoubleBackGroundColor"] != null ? (Color)ViewState["DoubleBackGroundColor"] : Color.Empty;
}
set
{
ViewState["DoubleBackGroundColor"] = value;
}
}
public Color ClickBackGroundColor
{
get
{
return ViewState["ClickBackGroundColor"] != null ? (Color)ViewState["ClickBackGroundColor"] : Color.Empty;
}
set
{
ViewState["ClickBackGroundColor"] = value;
}
}
public WebBarDataGrid()
{
this.BackColor = Color.Beige;
this.BorderColor = Color.Black;
this.ShowFooter = true;
this.SingleBackGroundColor = Color.Gainsboro;
this.DoubleBackGroundColor = Color.White;
this.ClickBackGroundColor = Color.LightBlue;
this.ClickBackGroundColor = Color.LightBlue;
this.FooterStyle.BackColor = Color.Tomato;
this.ForeColor = Color.Black;
this.AllowSorting = true;
}
//初始化DataGrid并添加全选模板列
protected override void OnInit(EventArgs e)
{
TemplateColumn gc = new TemplateColumn();
gc.HeaderText = "<input type='checkbox' id='cbAll" + this.ID + "' οnclick=/"checkAll(this.form," + "/'cbAll" + this.ID + "/');/"/>全选";
this.Columns.AddAt(0,gc);
base.OnInit(e);
}
protected override void OnSortCommand(DataGridSortCommandEventArgs e)
{
base.OnSortCommand (e);
if (e.SortExpression == GetViewState("SortField"))
{
if (GetViewState("SortMethod") == "ASC")
SetViewState("SortMethod","DESC");
else
SetViewState("SortMethod","ASC");
}
else
{
SetViewState("SortField",e.SortExpression);
SetViewState("SortMethod","ASC");
}
bindGrid();
}
/// <summary>
/// 从ViewState中获取某个属性值,如果该属性不存在,返回空字符串。
/// </summary>
/// <param name="PropertyName">属性名称</param>
/// <returns>属性值</returns>
public string GetViewState(string PropertyName)
{
try
{
return ViewState[PropertyName].ToString();
}
catch(NullReferenceException)
{
return "";
}
}
/// <summary>
/// 设置ViewState中某个属性的值
/// </summary>
/// <param name="PropertyName">属性名</param>
/// <param name="PropertyValue">属性值</param>
public void SetViewState(string PropertyName,string PropertyValue)
{
ViewState[PropertyName]=PropertyValue;
}
protected override void OnItemDataBound(DataGridItemEventArgs e)
{
dv = (DataView)this.DataSource;
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (e.Item.ItemIndex != -1)
{
if (e.Item.ItemIndex % 2 == 0)
{ e.Item.BackColor = this.SingleBackGroundColor; }
else
{ e.Item.BackColor = this.DoubleBackGroundColor; }
}
e.Item.Attributes["onclick"] = "checkOne('" + e.Item.ClientID.ToString() + "_cb" + e.Item.ItemIndex.ToString() + "',this,'" + (e.Item.ItemIndex % 2).ToString() + "');";
//e.Item.Attributes["ondblclick"] = "dblClick('" + e.Item.ItemIndex.ToString() + "','" + this.ClientID + "_hdSelectedRowId')";
e.Item.Attributes["onmouseover"]="this.style.cursor='hand';";
e.Item.Attributes["onmouseout"] = "this.style.cursor='default';";
}
base.OnItemDataBound(e);
}
private void addFootItem(DataGridItemEventArgs e)
{
footTextBox1.Width = 25;
e.Item.Cells[0].ColumnSpan = this.Columns.Count;
for(int i=1;i<this.Columns.Count;i++)
e.Item.Cells[i].Visible = false;
footLabel1.Text = "记录总数 " +dv.Table.Rows.Count+" ";
if(this.PageCount>1)
{
footLabel1.Text += "每页";
e.Item.Cells[0].Controls.Add(footLabel1);
if(!this.Page.IsPostBack)
footTextBox1.Text = this.PageSize.ToString();
footTextBox1.EnableViewState=true;
e.Item.Cells[0].Controls.Add(footTextBox1);
this.btn.Click += new EventHandler(btn_Click);
btn.Text = "确定";
btn.Width=30;
e.Item.Cells[0].Controls.Add(btn);
footLabel2.Text = "条 当前页"+(this.CurrentPageIndex)+"/"+this.PageCount;
footLabel2.Text +=" 跳到 ";
Ddl.AutoPostBack = true;
Ddl.EnableViewState = true;
if(this.eventFlg.Text !="1")
{
Ddl.Items.Clear();
for(int i=1;i<=this.PageCount;i++)
Ddl.Items.Add(new ListItem(i.ToString(),i.ToString()));
}
this.Ddl.SelectedIndexChanged += new System.EventHandler(this.Ddl_SelectedIndexChanged_1);
e.Item.Cells[0].Controls.Add(footLabel2);
e.Item.Cells[0].Controls.Add(Ddl);
}
else
{
e.Item.Cells[0].Controls.Add(footLabel1);
}
}
protected override void OnPreRender(EventArgs e)
{
this.CreateSelectedRowItems();
string js = @"<script type='text/javascript'>
function checkOne(checkBoxId,row,ItemIndex)
{
if(document.getElementById(checkBoxId)==null){return;}
if(document.getElementById(checkBoxId).checked==true)
{
document.getElementById(checkBoxId).checked=false;
if(ItemIndex=='1')
{
row.style.backgroundColor='" + ColorTranslator.ToHtml(DoubleBackGroundColor) + @"';
}
else
{
row.style.backgroundColor='" + ColorTranslator.ToHtml(SingleBackGroundColor) + @"';
}
}
else
{
document.getElementById(checkBoxId).checked=true;
row.style.backgroundColor='" + ColorTranslator.ToHtml(ClickBackGroundColor) + @"';
}
}
function checkOneByBoxClick(checkBox,row,ItemIndex)
{
if(checkBox==null){return;}
if(checkBox.checked==true)
{
checkBox.checked=false;
}
else
{
checkBox.checked=true;
}
}
function checkAll(form, gvname)
{
for (var i=0;i<form.elements.length;i++)
{
var e = form.elements[i];
var s = e.name
var tt = s.substring(s.indexOf(':'),0);
if (e.name != gvname && tt ==gvname.substring(5))
{
e.checked = document.getElementById(gvname).checked;
}
}
}
function checkNumber(form)
{
for (var i=0;i<form.elements.length;i++)
{
var e = form.elements[i];
var s = e.name
var tt = s.substring(s.lastIndexOf(':')+1,s.length);
if (tt=='txtPageSize')
{
if((!isNaN(parseInt(e.value))))
{
return true;
}
else
{
alert('请输入正确的整数');
e.focus();
return false;
}
}
}
}
function dblClick(ItemIndex,objHiddenId)
{
document.getElementById(objHiddenId).value=ItemIndex;
__doPostBack('" + this.ID + @":HideButton','');
}
</script>";
this.Page.RegisterClientScriptBlock("GetType", js);
base.OnPreRender(e);
}
protected void CreateSelectedRowItems()
{
if (this.Items.Count > 0)
{
HtmlInputHidden hdSelectedRowId = (HtmlInputHidden)this.FindControl("hdSelectedRowId");
if (hdSelectedRowId == null)
{
hdSelectedRowId = new HtmlInputHidden();
hdSelectedRowId.ID = "hdSelectedRowId";
this.Controls.Add(hdSelectedRowId);
}
if (((Button)this.FindControl("HideButton")) == null)
{
this.HideButton.ID = "HideButton";
this.HideButton.Width = 0;
this.Controls.Add(this.HideButton);
}
}
}
protected override void OnItemCreated(DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
cb = new HtmlInputCheckBox();
cb.ID = "cb" + e.Item.ItemIndex.ToString();
cb.Value = e.Item.ItemIndex.ToString();
cb.Attributes["onclick"] = "checkOneByBoxClick(this,this.parent,'" + (e.Item.ItemIndex % 2).ToString() + "');";
e.Item.Cells[0].Controls.Add(cb);
e.Item.Cells[0].Width=50;
}
if(e.Item.ItemType == ListItemType.Pager )
{
if(this.DataSource != null)
{
dv = (DataView)this.DataSource;
addPagerItem(e,dv.Table.Rows.Count);
}
}
base.OnItemCreated(e);
}
private void addPagerItem(DataGridItemEventArgs e,int Itemcount)
{
if(footTextBox1.Text!="")
this.PnSizeLab.Text = "("+footTextBox1.Text+")";
else
this.PnSizeLab.Text = this.PageSize.ToString();
e.Item.Cells[0].Controls.Clear();//注意
footTextBox1.Width = 25;
footLabel1.Text = "记录总数 " +dv.Table.Rows.Count+" ";
footLabel1.Text += "每页";
e.Item.Cells[0].Controls.Add(footLabel1);
e.Item.Cells[0].Controls.Add(PnSizeLab);
this.footTextBox1.Text=this.PageSize.ToString();
this.footTextBox1.ID="txtPageSize";
e.Item.Cells[0].Controls.Add(footTextBox1);
//提交改变页记录数按钮
btn.Attributes["onclick"]="javascript:return checkNumber(this.form);";//判断输入是否为整数
this.btn.Click += new EventHandler(btn_Click);
btn.Text = "确定";
btn.Width=30;
e.Item.Cells[0].Controls.Add(btn);
//上一页、下一页按钮
btnnext.Text = " 下一页 ";
btnprev.Text = " 上一页 ";
btnnext.Click +=new EventHandler(btnnext_Click);
this.btnprev.Click +=new EventHandler(btnprev_Click);
if(this.CurrentPageIndex==0)
this.btnprev.Enabled = false;
else
this.btnprev.Enabled = true;
if(this.CurrentPageIndex==this.PageCount-1)
this.btnnext.Enabled = false;
else
this.btnnext.Enabled = true;
e.Item.Cells[0].Controls.Add(btnprev);
e.Item.Cells[0].Controls.Add(btnnext);
//当前页提示
footLabel2.Text = "条 当前页"+(this.CurrentPageIndex+1)+"/"+this.PageCount;
e.Item.Cells[0].Controls.Add(footLabel2);
//跳页下拉框
jumpLabel1.Text=" 跳到";
e.Item.Cells[0].Controls.Add(jumpLabel1);
Ddl.AutoPostBack = true;//注意这个属性
Ddl.EnableViewState = true;//注意这个属性
Ddl.Items.Clear();
for(int i=1;i<=this.PageCount;i++)
Ddl.Items.Add(new ListItem(i.ToString(),i.ToString()));
Ddl.SelectedIndex=this.CurrentPageIndex;
this.Ddl.SelectedIndexChanged += new System.EventHandler(this.Ddl_SelectedIndexChanged_1);
e.Item.Cells[0].Controls.Add(Ddl);
jumpLabel2.Text="页";
e.Item.Cells[0].Controls.Add(jumpLabel2);
//添加导出EXCEL按钮
this.excebtn.Text = "记录导出为EXCEL";
e.Item.Cells[0].Controls.Add(excebtn);
this.excebtn.Click +=new EventHandler(excebtn_Click);
}
private void btn_Click(object sender,EventArgs e)
{
this.PageSize= Int16.Parse(this.footTextBox1.Text);
this.eventFlg.Text ="1";
this.CurrentPageIndex = 0;
bindGrid();
}
private void btnnext_Click(object sender,EventArgs e)
{
if(this.CurrentPageIndex<this.PageCount-1&&countflg==0)
{
this.CurrentPageIndex = this.CurrentPageIndex+1;
countflg=1;
}
bindGrid();
}
private void btnprev_Click(object sender,EventArgs e)
{
if(this.CurrentPageIndex>=1&&countflg==0)
{
this.CurrentPageIndex = this.CurrentPageIndex-1;
countflg=1;
}
bindGrid();
}
private void excebtn_Click(object sender,EventArgs e)
{
bindGrid();
dv = (DataView)this.DataSource;
int k=0;
HeaderText = new String[this.Columns.Count];
//填充表头
for (int i=0 ;i<this.Columns.Count;i++)
{
string colType = this.Columns[i].GetType().ToString();
if (colType == "System.Web.UI.WebControls.BoundColumn")
{
k=k+1;
HeaderText[i] = this.Columns[i].HeaderText;
}
}
ProduceCSV(this,dv);
}
private void Ddl_SelectedIndexChanged_1(object sender, System.EventArgs e)
{
this.CurrentPageIndex = Convert.ToInt32((Convert.ToInt32(Ddl.SelectedValue)-1));
bindGrid();
}
private void bindGrid()
{
if (GetViewState("SortField") != "" && GetViewState("SortMethod")!="")
dv.Sort = GetViewState("SortField") +" " + GetViewState("SortMethod");
this.DataSource = dv;
this.DataBind();
}
public string SelectRows()
{
string selectIndex = "";
foreach (DataGridItem row in this.Items)
{
if (row.ItemType == ListItemType.Item)
{
HtmlInputCheckBox cb = (HtmlInputCheckBox)row.Cells[0].FindControl("cb" + row.ItemIndex.ToString());
if (cb == null) continue;
if (cb.Checked)
{
selectIndex += "," + cb.Value;
}
}
}
if (selectIndex!="") { selectIndex = selectIndex.Substring(1); }
else { return null; }
return selectIndex;
}
public void ProduceCSV(DataGrid dgListBill,DataView adv)
{
if(adv != null && adv.Table.Rows.Count>0)
{
int colCount = adv.Table.Columns.Count;
int valueRowCount = adv.Table.Rows.Count;
string[] dtHeader = new String[colCount];
string strLine;
StringWriter sw=new StringWriter();
strLine ="";
//填充表头
for (int i=0 ;i<HeaderText.Length;i++)
{
if(HeaderText[i]!="" && HeaderText[i]!=null)
{
if(strLine=="")
strLine += HeaderText[i];
else
strLine += " "+HeaderText[i];
}
}
sw.WriteLine(strLine);
// //填充内容
sw.WriteLine(adv.Table.Rows.Count);
for(int i = 0;i<adv.Table.Rows.Count;i++)
{
strLine ="";
for(int j=0;j<adv.Table.Columns.Count;j++)
{
strLine += GetWriteableValue(adv.Table.Rows[i][j].ToString())+" ";
}
sw.WriteLine(strLine);
}
ResponseAttach(sw,"Result.xls","application/ms-excel","attachment","gb2312");
sw.Close();
}
}
public static string GetWriteableValue(object o)
{
if(o==null || o == Convert.DBNull)
return "";
else if(o.ToString().IndexOf(" ")==-1)
return o.ToString();
else
return "/t" + o.ToString() + "/t";
}
/// <summary>
/// 向客户端输出文件
/// </summary>
/// <param name="fileData">文件数据</param>
/// <param name="strFileName">文件名</param>
/// <param name="ContentType">文件类型</param>
/// <param name="OpMethod">输出方式:attachment,on-line</param>
public void ResponseAttach(StringWriter fileData,string strFileName,string ContentType,string OpMethod,string EncodingName)
{
this.Page.Response.Clear();
this.Page.Response.Charset = "GB2312";
this.Page.Response.ContentEncoding = System.Text.Encoding.Unicode;
this.Page.Response.ContentType = ContentType;
this.Page.Response.AppendHeader("Content-Disposition", OpMethod+";filename="+strFileName);
this.Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding(EncodingName);
this.Page.Response.Write(fileData.ToString());
this.Page.Response.End();
this.Page.Response.Clear();
}
}
}