gridview高级应用
修改背景颜色与添加交互效果
添加鼠标移动事件
添加单击事件
添加键盘事件
添加修改背景颜色事件
使用模板列
添加全选效果
添加删除确认效果
添加图片显示效果
导出到EXCEL文件
.ashx文件处理IHttpHandler实现发送文本及二进制数据的方法。
不使用数据源控件的GridView
_________________________________________________________________________
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
修改背景颜色与添加交互效果
-------------------------------------------------------------
// RowCreated方法添加列元素属性
if(e.Row.RowType==DataControlRowType.DataRow)//如果行的类型为数据行(有表头行)
{
e.Row.Attributes.Add("onmouseover","currentcolor=this.style.backgroundColor;this.style.backgroundColor='#COCOFF';this.style.cursor='hand';");
e.Row.Attributes.Add("onmouseout","this.style.backgroundColor=currentcolor");
}
------------------------------------------------------------------
// RowDataBound行数据加载时
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[8].Text == "USA")
{
//e.Row.BackColor = System.Drawing.Color.Red;
e.Row.Cells[8].BackColor = System.Drawing.Color.Red;
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
--------------------------------------------------
全选和取消全选
---------------------------
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
int i;
if (((CheckBox)sender).Checked)
{
for (i = 0; i < GridView1.Rows.Count; i++)
{
//找出Gridview里面的CheckBox
((CheckBox)GridView1.Rows[i].FindControl("CheckBox1")).Checked = true;
}
}
else
{
for (i = 0; i < GridView1.Rows.Count; i++)
{
((CheckBox)GridView1.Rows[i].FindControl("CheckBox1")).Checked =false;
}
}
}
--------------------------------------------------
添加键盘事件
---------------------------------------
调用页面
<script language=javascript>
function openpage(htmlurl)
{
var newwin=window.open(htmlurl,"newWin","toolbar=no,location=no,directories=no,status=no,scrollbars=yes,menubar=no,resizable=yes,top=100,left=200,width=650,height=300");
newwin.focus();
return false;
}
</script>
<input type=button value="调用" οnclick="return openpage('GridViewClientClick.aspx');" />
-------------------------------------------------
被调用页
<script language=javascript>
function GridViewItemKeyDownEvent(d)
{
window.alert("事件类型: GridViewItemKeyDownEvent 作用对象: " + d);
}
function ReKey(k)
{
//window.opener打开子窗体的父窗体
window.opener.document.getElementById('name').value=k;
window.close();
}
</script>
// RowDataBound行数据加载时
if(e.Row.RowType==DataControlRowType.DataRow)
{
e.Row.Attributes.Add("ondblclick", "ReKey('" + e.Row.Cells[2].Text+"')");
e.Row.Attributes["style"] = "Cursor:hand";
//键盘事件
e.Row.Attributes.Add("OnKeyDown", "GridViewItemKeyDownEvent('" + e.Row.Cells[1].Text + "')");
}
----------------------------------------------
弹出确认窗口
在按钮中添加 OnClientClick=return confirm("确认删除")
模板列数据绑定
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Literal ID="Literal1" runat="server" Text='<%# Eval("FirstName", "{0}")+" "+Eval("LastName", "{0}") %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Photo">
<ItemTemplate>
<img src='GetImage.ashx?eid=<%#Eval("EmployeeID")%>' />
</ItemTemplate>
</asp:TemplateField>
.ashx文件处理IHttpHandler实现发送文本及二进制数据的方法。
HttpHandler是一个彻底自定义Http请求的方法,它通过web.config来定义Asp.Net运行时来过滤出要自定义的Http请求,发送到定义在web.config的指定类中。
<%@ WebHandler Language="C#" Class="GetImage" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data.Sql;
public class GetImage : IHttpHandler {
public void ProcessRequest (HttpContext context) {
using (SqlConnection sc = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
sc.Open();
String txtsql = "select photo from employees where employeeid=" + context.Request.QueryString["eid"];
SqlCommand scd = new SqlCommand(txtsql, sc);
context.Response.Clear();
context.Response.ContentType = "image/bmp";
byte[] bitmapBytes = (byte[])scd.ExecuteScalar();
int length = bitmapBytes.Length;
context.Response.OutputStream.Write(bitmapBytes, 78, bitmapBytes.Length - 78);
context.Response.Cache.SetCacheability(HttpCacheability.Public);
}
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
------------------------------------------------------
导出到EXCEL文件
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
// 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm( Control control )
{ } //这个要加上不然会报错
不使用数据源控件的GridView
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewDataBind();
}
}
public void GridViewDataBind()
{
Button1.Enabled = true;
Button2.Enabled = true;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
try
{
conn.Open();
SqlDataAdapter sa = new SqlDataAdapter("select * from customers where 1=2", conn);
DataSet ds = new DataSet();
sa.Fill(ds, "customers");
if (ds.Tables[0].Rows.Count == 0)
{
AddDummyData(ds);
}
GridView1.DataSource = ds.Tables["customers"];
GridView1.AllowPaging = true;
GridView1.PageSize = 5;
GridView1.DataBind();
conn.Close();
if (GridView1.PageIndex == 0)
{
Button1.Enabled = false;
}
if (GridView1.PageIndex == GridView1.PageCount - 1)
{
Button2.Enabled = false;
}
}
catch
{
}
finally
{
conn.Close();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridViewDataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.PageIndex = GridView1.PageIndex - 1;
GridViewDataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
GridView1.PageIndex = GridView1.PageIndex + 1;
GridViewDataBind();
}
protected void Button3_Click(object sender, EventArgs e)
{
GridView1.PageIndex = GridView1.PageCount - 1;
GridViewDataBind();
}
protected void Button4_Click(object sender, EventArgs e)
{
GridView1.PageIndex = 0;
GridViewDataBind();
}
private void AddDummyData(DataSet ds)
{
// Add a dummy row
DataTable dt = ds.Tables[0];
DataRow newRow = dt.NewRow();
dt.Rows.Add(newRow);
}