您的位置:首页 > 其它

DataGrid系列技巧(导出excel,事件,多种方式呈现数据,全选全删)等等等

2006-05-04 10:17 751 查看
内容有点多,建议自己练下,然后放那里,一忽肯定有用得着的时候!




前台页HTML
1



<%

@ Page language="c#" Codebehind="datagrid_a.aspx.cs" AutoEventWireup="false" Inherits="databind.datagrid_a" %>
2

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
3

<HTML>
4

<HEAD>
5

<title>datagrid_a</title>
6

<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
7

<meta content="C#" name="CODE_LANGUAGE">
8

<meta content="JavaScript" name="vs_defaultClientScript">
9

<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
10

</HEAD>
11

<body MS_POSITIONING="GridLayout">
12

<form id="Form1" method="post" runat="server">
13

<asp:datagrid id="dg" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 72px" runat="server"
14

AutoGenerateColumns="False" PageSize="3" AllowPaging="True" BorderColor="#CCCCCC" BorderWidth="1px"
15

Width="912px" ShowFooter="True" BorderStyle="None" BackColor="White" CellPadding="4" GridLines="Horizontal"
16

ForeColor="Black">
17

<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#CC3333"></SelectedItemStyle>
18

<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#333333"></HeaderStyle>
19

<FooterStyle ForeColor="Black" BackColor="#CCCC99"></FooterStyle>
20

<Columns>
21

<asp:BoundColumn DataField="id" SortExpression="id" HeaderText="ID"></asp:BoundColumn>
22

<asp:BoundColumn DataField="name" HeaderText="名字"></asp:BoundColumn>
23

<asp:BoundColumn DataField="sex" SortExpression="sex" HeaderText="原始sex"></asp:BoundColumn>
24

<asp:TemplateColumn HeaderText="修改后sex">
25

<ItemTemplate>
26

<FONT face="宋体">
27

<asp:RadioButton id=RadioButton1 runat="server" Checked='<%# DataBinder.Eval(Container,"DataItem.sex") %>' GroupName="sex" Text="男" Enabled="False">
28

</asp:RadioButton>
29

<asp:RadioButton id=RadioButton2 runat="server" Checked='<%# !(bool)DataBinder.Eval(Container,"DataItem.sex") %>' GroupName="sex" Text="女" Enabled="False">
30

</asp:RadioButton></FONT>
31

</ItemTemplate>
32

<EditItemTemplate>
33

<FONT face="宋体">
34

<asp:RadioButton id="RadioButton3" runat="server" Checked='<%# DataBinder.Eval(Container,"DataItem.sex") %>' GroupName="sex" Text="男">
35

</asp:RadioButton>
36

<asp:RadioButton id="RadioButton4" runat="server" Checked='<%# !(bool)DataBinder.Eval(Container,"DataItem.sex") %>' GroupName="sex" Text="女">
37

</asp:RadioButton></FONT>
38

</EditItemTemplate>
39

</asp:TemplateColumn>
40

<asp:TemplateColumn HeaderText="自定义性别">
41

<HeaderTemplate>
42

<FONT face="宋体">
43

<asp:Label id="Label2" runat="server">性别</asp:Label></FONT>
44

</HeaderTemplate>
45

<ItemTemplate>
46

<FONT face="宋体">
47

<asp:DropDownList id="sex" runat="server" Enabled="False">
48

<asp:ListItem Value="True">男</asp:ListItem>
49

<asp:ListItem Value="False">女</asp:ListItem>
50

</asp:DropDownList></FONT>
51

</ItemTemplate>
52

<EditItemTemplate>
53

<asp:DropDownList id="sex1" runat="server">
54

<asp:ListItem Value="True">男</asp:ListItem>
55

<asp:ListItem Value="False">女</asp:ListItem>
56

</asp:DropDownList>
57

</EditItemTemplate>
58

</asp:TemplateColumn>
59

<asp:BoundColumn DataField="brod" HeaderText="生日" DataFormatString="{0:yyyy}"></asp:BoundColumn>
60

<asp:TemplateColumn HeaderText="分数">
61

<ItemTemplate>
62

<asp:Label id=Label3 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.num") %>'>
63

</asp:Label>
64

</ItemTemplate>
65

<FooterTemplate>
66

<FONT face="宋体"></FONT>
67

</FooterTemplate>
68

<EditItemTemplate>
69

<asp:TextBox id=TextBox1 runat="server" Width="72px" Text='<%# DataBinder.Eval(Container, "DataItem.num") %>'>
70

</asp:TextBox>
71

</EditItemTemplate>
72

</asp:TemplateColumn>
73

<asp:ButtonColumn Text="选择" HeaderText="选择" CommandName="Select"></asp:ButtonColumn>
74

<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="更新" HeaderText="编辑" CancelText="取消" EditText="编辑"></asp:EditCommandColumn>
75

<asp:ButtonColumn Text="删除" HeaderText="删除" CommandName="Delete"></asp:ButtonColumn>
76

<asp:TemplateColumn HeaderText="自定义删除">
77

<ItemTemplate>
78

<FONT face="宋体">
79

<asp:Button id="btnde" runat="server" Text="删除" CommandName="userde"></asp:Button></FONT>
80

</ItemTemplate>
81

</asp:TemplateColumn>
82

<asp:TemplateColumn HeaderText="全选">
83

<HeaderTemplate>
84

<FONT face="宋体">
85

<asp:CheckBox id="chkall" runat="server" OnCheckedChanged="chkall" Text="全选" AutoPostBack="True"></asp:CheckBox></FONT>
86

</HeaderTemplate>
87

<ItemTemplate>
88

<FONT face="宋体">
89

<asp:CheckBox id="chk" runat="server" Text="选择"></asp:CheckBox></FONT>
90

</ItemTemplate>
91

</asp:TemplateColumn>
92

</Columns>
93

<PagerStyle HorizontalAlign="Right" ForeColor="Black" BackColor="White"></PagerStyle>
94

</asp:datagrid><asp:literal id="Literal1" runat="server"></asp:literal><asp:literal id="Literal2" runat="server"></asp:literal>
95

<asp:Button id="btndelete" style="Z-INDEX: 102; LEFT: 80px; POSITION: absolute; TOP: 272px"
96

runat="server" Width="128px" Text="删除选中的行"></asp:Button>
97

<asp:Label id="Label1" style="Z-INDEX: 103; LEFT: 48px; POSITION: absolute; TOP: 328px" runat="server">在表格中控件,例如下拉列表或者RadioButton,因为做个例题我花的时间实在太多了,老婆在催出去走走,所以有兴趣的可以自己试下;)所以,您如果是完全复制我这两个页去做实验的话,<SPAN
98

style="COLOR: #ff0000"
99

twffan="done">别忘记了,导出代码虽然全部正确,但是在这个页却是不能用的!</SPAN><BR>前台页面:</asp:Label>
100

<asp:Button id="Button1" style="Z-INDEX: 104; LEFT: 232px; POSITION: absolute; TOP: 272px" runat="server"
101

Width="120px" Text="隐藏一列"></asp:Button>
102

<asp:Button id="Button2" style="Z-INDEX: 105; LEFT: 384px; POSITION: absolute; TOP: 272px" runat="server"
103

Text="导出EXCEL文件"></asp:Button></form>
104

</body>
105

</HTML>
106









后台CS代码
1

using System;
2

using System.Collections;
3

using System.ComponentModel;
4

using System.Data;
5

using System.Drawing;
6

using System.Web;
7

using System.Web.SessionState;
8

using System.Web.UI;
9

using System.Web.UI.WebControls;
10

using System.Web.UI.HtmlControls;
11

//添加I0命名空间
12

using System.IO;
13

using System.Data.OleDb;
14

namespace databind
15





{
16



/**//// <summary>
17

/// datagrid_a 的摘要说明。
18

/// </summary>
19

public class datagrid_a : System.Web.UI.Page
20





{
21

protected System.Web.UI.WebControls.Literal Literal1;
22

protected System.Web.UI.WebControls.Literal Literal2;
23

protected System.Web.UI.WebControls.Button btndelete;
24

protected System.Web.UI.WebControls.Label Label1;
25

protected System.Web.UI.WebControls.Button Button1;
26

protected System.Web.UI.WebControls.Button Button2;
27

protected System.Web.UI.WebControls.DataGrid dg;
28


29

private void Page_Load(object sender, System.EventArgs e)
30





{
31

this.btndelete.Attributes.Add("onclick","return confirm('你真的要删除所选的项吗?')");
32

if(!IsPostBack)
33





{
34

fill();
35

}
36


37

}
38


39



Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
40

override protected void OnInit(EventArgs e)
41





{
42

//
43

// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
44

//
45

InitializeComponent();
46

base.OnInit(e);
47

}
48


49



/**//// <summary>
50

/// 设计器支持所需的方法 - 不要使用代码编辑器修改
51

/// 此方法的内容。
52

/// </summary>
53

private void InitializeComponent()
54





{
55

this.dg.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dg_ItemCreated);
56

this.dg.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dg_PageIndexChanged);
57

this.dg.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dg_CancelCommand);
58

this.dg.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dg_EditCommand);
59

this.dg.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dg_ItemDataBound);
60

this.btndelete.Click += new System.EventHandler(this.btndelete_Click);
61

this.Button1.Click += new System.EventHandler(this.Button1_Click);
62

this.Button2.Click += new System.EventHandler(this.Button2_Click);
63

this.Load += new System.EventHandler(this.Page_Load);
64


65

}
66

#endregion
67


68

private void fill()
69





{
70

OleDbConnection odb=new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source="+Server.MapPath("//databind//db.mdb")+";");
71

OleDbDataAdapter oda=new OleDbDataAdapter();
72

oda.SelectCommand=new OleDbCommand("select * from sex order by id asc",odb);
73

DataSet ds=new DataSet();
74

oda.Fill(ds,"sex");
75

dg.DataSource=ds.Tables["sex"];
76

dg.DataKeyField="id";
77

dg.DataBind();
78

foreach(DataGridItem dl in dg.Items)//迭代集合
79





{
80

//以下是非编辑状态的下拉列表
81

DropDownList ddl=(DropDownList)dl.FindControl("sex");//找到sex控件并交给ddl
82

if(ddl!=null)
83





{
84

string sex=ds.Tables["sex"].Rows[dl.ItemIndex][2].ToString();
85

if(sex=="True")
86





{
87

ddl.SelectedValue="True";
88

}
89

else
90





{
91

ddl.SelectedValue="False";
92

}
93

}
94

//以下是可编辑状态的下拉列表
95

DropDownList dde=(DropDownList)dl.FindControl("sex1");//找到sex控件并交给ddl
96

if(dde!=null)
97





{
98

// string sex=ds.Tables["sex"].Rows[dl.ItemIndex][2].ToString();//得出sex的值
99

// if(sex=="True")
100

// {
101

// dde.SelectedValue="True";
102

// }
103

// else
104

// {
105

// dde.SelectedValue="False";
106

// }
107

dde.SelectedValue=ds.Tables["sex"].Rows[dl.ItemIndex][2].ToString();
108

//其实这样更省事,只是因为sql数据库不支持bool类型,所以必然会出现在SQL库里,这里是其他的,需要转换
109

}
110

int numm=0;
111

for(int i=0;i<dg.Items.Count;i++)//使用循环
112





{
113

numm+=Convert.ToInt32(ds.Tables["sex"].Rows[i]["num"].ToString());
114

//得出总和,这里如果是求全部人的分,一定要用数据库,而别用表格中的数字相加,因为我刚才犯了这一错,结果老整不对
115

}
116

int avn=numm/dg.Items.Count;//求平均分
117

foreach(DataGridItem dll in dg.Controls[0].Controls)//在子层中再循环
118





{
119

if(dll.ItemType==ListItemType.Footer)//如果模板类型是页脚
120





{
121

dll.Cells[6].Text=avn.ToString();//那么在页脚里面写上平均分
122

}
123

}
124


125

}
126

}
127

private void dg_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
128





{//触发编辑选择行
129

dg.EditItemIndex=e.Item.ItemIndex;
130

fill();
131

}
132


133

private void dg_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
134





{//翻页功能
135

dg.CurrentPageIndex=e.NewPageIndex;
136

fill();
137

}
138


139

private void dg_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
140





{//取消编辑
141

dg.EditItemIndex=-1;
142

fill();
143

}
144

public void chkall(object Sender, System.EventArgs e)
145





{//字定义的动作,该动作发生事件源是自己的前面Datagrid的全选项模板的头模板项中增加的一个OnCheckedChanged="chkall"
146

CheckBox cb=(CheckBox)Sender;//初始化一个复选按纽.并把事件发生的源对象Sender转化后赋值给它
147

if(cb.Text=="全选")
148





{
149

foreach(DataGridItem dl in dg.Items)//迭代表格中所有行
150





{
151

CheckBox cbl=(CheckBox)dl.FindControl("chk");//查找名字为chk的控件,并强制类型转换为Checkbox类赋值给cbl
152

cbl.Checked=cb.Checked;//让该控件的选中状态和头模板中的复选框同步
153

}
154

}
155

}
156

private void btndelete_Click(object sender, System.EventArgs e)
157





{//该按纽也有个客户端事件,让用户确认是否真的删除,这句加到load事件中的..啊?这句是什么?看了下面就知道了
158

foreach(DataGridItem dl in dg.Items)//也要迭代表格中所有行
159





{
160

CheckBox cb=(CheckBox)dl.FindControl("chk");//找到每行的复选框
161

if(cb.Checked)//如果他被选中了
162





{
163

string id=dl.Cells[0].Text.ToString();//利用迭代,得到他的第一列的值
164

Response.Write(id+"<br>");
165

}
166

}
167

dg.CurrentPageIndex=0;//把当前页码赋值为 0
168

fill();//重新绑定
169

}
170

private void dg_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)//这些事件名称都是固定的,
171





{//在前面名叫 dg 的datagrid中,我们加了一个模板列,在模板列中放了一个按纽(btnde)
172

switch(e.Item.ItemType)//循环判断
173





{
174

case ListItemType.Item://如果是项
175

case ListItemType.AlternatingItem://如果是交替项
176

case ListItemType.EditItem://如果是编辑项
177

Button btn=(Button)e.Item.FindControl("btnde");//找到名为btnde的按纽
178

btn.Text="94要删了你";//给按纽上的文字赋值
179

btn.Attributes.Add("onclick","return confirm('确认删除第"+e.Item.ItemIndex.ToString()+"行吗?')");//动作,确认删除
180

break;
181

}
182

}
183


184

private void dg_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)//这些事件名称都是固定的,
185





{//下面我们用另种方式来判断,就当是复习吧,
186

if(e.Item.ItemType==ListItemType.AlternatingItem||e.Item.ItemType==ListItemType.EditItem||e.Item.ItemType==ListItemType.Item)//也是判断当前项的类型的
187





{
188

e.Item.Attributes.Add("onmouseover","c=this.style.backgroundColor;this.style.backgroundColor='#0066ff'");//鼠标来了,读出当前行现在背景色,并把背景色换成指定的
189

e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=c");//鼠标走了,把背景色还原成开始的
190


191

OleDbConnection odb=new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source="+Server.MapPath("//databind//db.mdb")+";");//读数据库
192

OleDbDataAdapter oda=new OleDbDataAdapter();//实例化时局适配器
193

oda.SelectCommand=new OleDbCommand("select * from sex order by id asc",odb);//读取数据
194

DataSet ds=new DataSet();//实例化本地内存库
195

oda.Fill(ds,"sex");//装载数据到本地表sex
196

DataTable dt=ds.Tables["sex"];//把内存库中的sex表交给 dt 表
197

string name=dt.Rows[(int)e.Item.ItemIndex][1].ToString();//读出数据表中的 当前行,第二列的数据
198

((LinkButton)e.Item.Cells[9].Controls[0]).Attributes.Add("onclick","return confirm('确定删除("+name+")?')");//确认动作
199

}
200

//下面动作的控制编辑状态下的TextBox宽度的
201

if(e.Item.ItemType==ListItemType.EditItem)//因为这个只控制编辑状态下的文本框宽度
202





{
203

for(int i=0;i<e.Item.Cells.Count;i++)//循环当前项所有元素
204





{
205

if(e.Item.Cells[i].Controls.Count>0)//如果子控件数量大于0
206





{
207

try
208





{
209

TextBox tb=(TextBox)e.Item.Cells[i].Controls[0];//找出textbox控件并转换成TextBox再赋值给 tb
210

tb.Width=50;//设定他的宽度
211

}
212

catch(Exception a)
213





{
214

//不需要返回错误,麻烦
215

}
216

}
217

}
218

}
219

}
220


221

private void Button1_Click(object sender, System.EventArgs e)
222





{
223

int ss=3;//这个是自己设定的,你可以是0 ,1,2,3,4,5任意
224

dg.Columns[ss].Visible=false;//这个没有技术含量,但是,朋友写,在特殊的时候总有特殊的要求,呵呵!
225

}
226


227

private void Button2_Click(object sender, System.EventArgs e)
228





{//这个动作会和全选有冲突,
229

Response.ContentType="application/vnd.ms-excel";//指定内容类型
230

Response.Charset=""; //字符集是空,因为我也不知道到底有多少总,所以就空了,有兴趣的可以去研究下,别忘记告诉我下 我qq是 110535808
231

this.EnableViewState=false; //指定页请求结束时仍然保持现在状态
232

System.IO.StringWriter sw=new StringWriter();//将信息写如到字符串中
233

System.Web.UI.HtmlTextWriter hw=new HtmlTextWriter(sw);//说穿了就是把html格式一起给写进去了
234

dg.RenderControl(hw);//主题开始了,这里就开始把控件中内容输出到对象去
235

Response.Write(sw.ToString());
236

Response.End();
237

}
238


239

}
240

}
241






http://thcjp.cnblogs.com/archive/2006/05/01/390244.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: