这是后台代码
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data;
using System.IO;
using System.Data.OleDb;
using System.Data.ProviderBase;
using System.Data.SqlClient;
namespace WebApplication4
{
public partial class gridview : System.Web.UI.Page
{
private double sum;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
//GridView正反双向排序设置关键字,和升序还是降序
ViewState ["proID"]="proID";
ViewState["OrderDire"] = "Asc";
this.dataBind();
}
}
private void dataBind()
{
SqlConnection conn = DB.getConnection();
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand("select * from city ", conn);
DataSet ds = new DataSet();
sda.Fill(ds, "city");
this.GridView1.AllowPaging = true;
this.GridView1.PageSize = 4;
///在这个地方需要绑定主键 ,特别的注意啊
///
this.GridView1.DataKeyNames = new string[] { "cityID" };
//this.GridView1.DataSource = ds.Tables["city"];
///采用dataview
///
DataView dv = ds.Tables["city"].DefaultView;
///设置排序顺序以便在以后的方法中引用变量+kongge+排序方式即升序还是降序
string sort = (string)ViewState["proID"] + " " + (string)ViewState["OrderDire"];
dv.Sort = sort;
this.GridView1.DataSource = dv;
this.GridView1.DataBind();
//绑定后过滤,以突出显示某一行
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
DataRowView mydv = ds.Tables["city"].DefaultView[i];
string proid = Convert.ToString(mydv ["proID"]);
if (Convert.ToInt16(proid ) < 3)//大家这里根据具体情况设置可能ToInt32等等
{
GridView1.Rows[i].Cells[2].BackColor = System.Drawing.Color.Red;
}
}
conn.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
this.GridView1.EditIndex = e.NewEditIndex;
this.dataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Response.Write("test");
try
{
SqlConnection conn = DB.getConnection();
conn.Open();
string sqlstr = "upduate city set cityName='" + ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim()
+ "',proID='" + ((TextBox)(this.GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "'where cityID='" + this.GridView1.DataKeys[e.RowIndex].Value.ToString();
//Response.Write(sqlstr);
SqlCommand cmd = new SqlCommand(sqlstr, conn);
cmd.ExecuteNonQuery();
conn.Close();
this.GridView1.EditIndex = -1;
this.dataBind();
}
catch (Exception)
{
Response.Write("test");
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
//Response.Write(e.RowIndex);
string sqlstr = "delete from city where cityID= '" + this.GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
//Response.Write(sqlstr);
SqlConnection conn = DB.getConnection();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlstr, conn);
int count = cmd.ExecuteNonQuery();
//Response.Write(count);
conn.Close();
this.dataBind();
}
catch (Exception)
{
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.GridView1.EditIndex = -1;
//Response.Write("tes");
this.dataBind();
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
this.GridView1.SelectedIndex = e.NewSelectedIndex;
this.dataBind();
}
protected void GridView1_SelectedIndexChanging1(object sender, GridViewSelectEventArgs e)
{
this.GridView1.SelectedIndex = e.NewSelectedIndex;
string str = this.GridView1.DataKeys[e.NewSelectedIndex].Value.ToString() ;
Response .Write ("you selelecting is "+str );
}
/// <summary>
/// 该方法首先采用一个试图,在视图里面设置了排序方式
/// 然后和数据源绑定注意 排序只是改变了视图的表现而已,真的表并没有该变
/// 然后在排序事件中加入操作就可以了
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string spage = e.SortExpression;
//Response.Write(spage);
if (ViewState["proID"].ToString() == spage)
{
if (ViewState["OrderDire"].ToString() == "Desc")
{
ViewState["OrderDir"] = "Asc";
Response.Write("test1");
}
else
{
ViewState["OrderDire"] = "Desc";
Response.Write("test2");
}
}
else {
ViewState["proID"] = e.SortExpression;
}
this.dataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.GridView1.PageIndex = e.NewPageIndex;
this.dataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//当前行为-1行,
for(int i=-1;i<this.GridView1 .Rows .Count ;i++){
if (e.Row.RowType == DataControlRowType.DataRow) {
//当鼠标停留时更改背景色
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");
//当鼠标移开时还原背景色
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
try
{
Response.Write("do");
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript return confirm()");
}
catch (Exception) {
}
}
}
if (e.Row.RowIndex >= 0)
{
//必须扑捉的异常 !!!!!!!!!!!!!!
try
{
sum += Convert.ToDouble(e.Row.Cells[3].Text.ToString());
}
catch (Exception) {
}
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[2].Text = "总薪水为:";
e.Row.Cells[3].Text = sum.ToString();
e.Row.Cells[4].Text = "平均薪水为:";
e.Row.Cells[5].Text = ((sum /( Convert .ToDouble ( GridView1.Rows.Count.ToString ())))).ToString();
}
//Response.Write(" hell"+this.GridView1.Rows.Count.ToString ());
if (e.Row.RowIndex != -1)
{
int id = e.Row.RowIndex + 1;
e.Row.Cells[0].Text = id.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Export("application/ms-excel", "学生成绩报表.xls");
}
public void Export(string FileType, string FileName) {
try
{
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
this.GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
catch (Exception) {
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
this.GridView2.DataSource = this.getDataSet();
this.GridView2.DataBind();
}
private DataSet getDataSet() {
string sqlstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/upload/excel.xls") + ";Extended Properties=Excel 8.0;";
OleDbConnection oledb = new OleDbConnection(sqlstr);
OleDbDataAdapter mayda = new OleDbDataAdapter("select * from [sheet1$]", oledb);
DataSet ds = new DataSet();
mayda.Fill(ds);
return ds;
}
}
}
这是前台代码,<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="gridview.aspx.cs" Inherits="WebApplication4.gridview" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<style type ="text/css" >
.Freezing
{
position:relative ;
table-layout:fixed;
z-index: 10;
}
.Freezing th{overflow:hidden;white-space: nowrap;padding:2px;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" Height="588px">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating"
BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px"
CellPadding="4" onselectedindexchanging="GridView1_SelectedIndexChanging1"
AllowSorting="True" onpageindexchanging="GridView1_PageIndexChanging"
onrowdatabound="GridView1_RowDataBound" onsorting="GridView1_Sorting" ShowFooter="True"
>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<RowStyle BackColor="White" ForeColor="#003399" />
<Columns>
<asp:BoundField DataField="cityID" HeaderText="编号" ReadOnly="True"
SortExpression="cityID" />
<asp:BoundField DataField="cityID" HeaderText="cityID" ReadOnly="True" />
<asp:BoundField DataField="cityName" HeaderText="cityName" />
<asp:BoundField DataField="proID" HeaderText="proID" SortExpression="proID" />
<asp:CommandField ButtonType="Button" HeaderText="选择" ShowCancelButton="False"
ShowSelectButton="True" />
<asp:CommandField ButtonType="Button" HeaderText="编辑" ShowEditButton="True" />
<asp:CommandField ButtonType="Button" HeaderText="删除" ShowDeleteButton="True" />
<asp:HyperLinkField DataNavigateUrlFields="proID"
DataNavigateUrlFormatString="~/Default.aspx?proID={0}""
DataTextField="proID"
HeaderImageUrl="~/upload/u=1997936408,1812532572&fm=3&gp=1[1].jpg"
HeaderText="字段传值 超链接" Target="_blank" Text="Ok" />
</Columns>
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" CssClass="Freezing" />
</asp:GridView>
<asp:Label ID="Label1" runat="server"
Text="DataNavigateUrlFields是链接的字段名,DataNavigateUrlFormatString是路径"></asp:Label>
<asp:GridView ID="GridView2" runat="server" Width="396px">
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" οnclick="Button1_Click" Text="下载" />
<asp:Button ID="Button2" runat="server" Text="读取xls" οnclick="Button2_Click" />
</asp:Panel>
<center >
<h3 >DataFormatString="{0:M-dd-yyyy}" 用来改变日期的格式</h3>
</center>
</div>
</form>
</body>
</html>
由于本人初学,程序设计的不是很好,控件都没有改名字,不过该控件显现了至少10个小功能对初学者来说,还可以