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);
}