1、GridView无代码分页排序:
(1).AllowSorting设为True,aspx代码中是AllowSorting="True";
(2).默认1页10条,如果要修改每页条数,修改PageSize即可,在aspx代码中是PageSize="12"。
(3).默认的是单向排序的,右击GridView弹出“属性”,选择AllowSorting为True即可。
2.GridView选中,编辑,取消,删除:
前台代码:
。。。。。。
<asp:GridView ID="GridView1" runat="server" Height="133px" Width="539px" AutoGenerateColumns="False" DataKeyNames="id"
OnRowEditing="GridView1_RowEditing" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3"
CellSpacing="1" GridLines="None" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDataBound="GridView1_RowDataBound" OnRowDeleting="GridView1_RowDeleting" > <Columns> <asp:BoundField DataField="name" HeaderText="姓名" /> <asp:BoundField DataField="id" HeaderText="编号" DataFormatString="{0:000#}" ReadOnly="True" /> <asp:BoundField DataField="score" HeaderText="分数" /> <asp:CheckBoxField DataField="member" HeaderText="是否会员" ReadOnly="True" /> <asp:CommandField HeaderText="编辑" ShowEditButton="True" /> <asp:CommandField HeaderText="选择" ShowSelectButton="True" /> <asp:CommandField HeaderText="删除" ShowDeleteButton="True" /> </Columns> <RowStyle BackColor="#DEDFDE" ForeColor="Black" /> <FooterStyle BackColor="#C6C3C6" ForeColor="Black" /> <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" /> <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" /> </asp:GridView>
后台代码:
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class capital2_IDU : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { DataBindings(); } }
//数据绑定 public void DataBindings() { this.GridView1.DataSource = GetStudentInfo(); this.GridView1.DataBind(); } public DataSet GetStudentInfo() { DataSet dt = null; using (SqlConnection sqlcon = new SqlConnection(DBHelper.con)) { dt=DBHelper.GetStudentInfo(sqlcon, "select * from student"); sqlcon.Close(); } return dt; }
//编辑 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; DataBindings(); }
//更新 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { //GridViewRow row = GridView1.Rows[e.RowIndex]; //int ID = int.Parse(GridView1.DataKeys[e.RowIndex].Values[0].ToString()); //string userName = ((TextBox)row.FindControl("UserName")).Text.ToString(); //double Money = Convert.ToDouble(((TextBox)row.FindControl("Money")).Text.ToString()); GridViewRow row = GridView1.Rows[e.RowIndex]; //int ID=row.Cells[1].Text int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString()); string name = ((TextBox)(row.Cells[0].Controls[0])).Text; string score = ((TextBox)(row.Cells[2].Controls[0])).Text.Trim(); using (SqlConnection sqlcon = new SqlConnection(DBHelper.con)) { SqlDataReader dr; string sql = "Update student Set name='" + name + "',score='" + score + "' Where ID=" + ID + ""; SqlCommand myCommand = new SqlCommand(sql, sqlcon); sqlcon.Open(); dr = myCommand.ExecuteReader(); //获取或设置要编辑的行的索引。默认值为 -1,指示没有正在编辑的行 .取消编辑状态。 //将gridview从编辑模式切换成浏览模式 GridView1.EditIndex = -1; sqlcon.Close(); } DataBindings(); }
//删除 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { GridViewRow row = GridView1.Rows[e.RowIndex]; string ID = GridView1.DataKeys[e.RowIndex].Values[0].ToString().Trim(); using (SqlConnection sqlcon = new SqlConnection(DBHelper.con)) { SqlDataReader dr; string sql = "delete from student where ID=" + ID; SqlCommand myCommand = new SqlCommand(sql, sqlcon); sqlcon.Open(); dr = myCommand.ExecuteReader(); sqlcon.Close(); } Response.Write("<script type='text/javascript'>window.alert('删除成功')</script>"); DataBindings(); }
//取消编辑 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { this.GridView1.EditIndex = -1; DataBindings(); }
//绑定每一行触发该事件,此处为了给cell添加属性 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //绑定数据行 if (e.Row.RowType == DataControlRowType.DataRow) { if(e.Row.RowState==DataControlRowState.Normal|| e.Row.RowState==DataControlRowState.Alternate) { ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("OnClick", "javascript: return confirm('你确认要删除\"" + e.Row.Cells[0].Text.Trim() + "\"吗?')"); //鼠标经过时,行背景色变 e.Row.Attributes.Add("onmouseover","this.style.backgroundColor='#E6F5FA'"); //鼠标移出时,行背景色变 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#DEDFDE'"); } } } }
3、GridView和CheckBox结合:
点击更新时,需要获取checkbox值。
后台代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class capital2_IDU1 : System.Web.UI.Page
{
private int sum = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)//相当重要
{
DataBindings();
}
}
//绑定数据
public void DataBindings()
{
this.GridView1.DataSource = GetStudentInfo();
this.GridView1.DataBind();
}
public DataSet GetStudentInfo()
{
DataSet dt = null;
using (SqlConnection sqlcon = new SqlConnection(DBHelper.con))
{
dt = DBHelper.GetStudentInfo(sqlcon, "select * from student");
sqlcon.Close();
}
return dt;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
//删除数据 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) {
//获取关键字值
GridViewRow row = GridView1.Rows[e.RowIndex];
string ID = GridView1.DataKeys[e.RowIndex].Values[0].ToString().Trim();
using (SqlConnection sqlcon = new SqlConnection(DBHelper.con))
{
SqlDataReader dr;
string sql = "delete from student where ID=" + ID;
SqlCommand myCommand = new SqlCommand(sql, sqlcon);
sqlcon.Open();
dr = myCommand.ExecuteReader();
sqlcon.Close();
}
Response.Write("<script type='text/javascript'>window.alert('删除成功')</script>");
DataBindings();
}
//点击编辑按钮
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
//点击编辑后,页面刷新,数据丢失,所以再次绑定
DataBindings();
}
//更新数据 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridView1.Rows[e.RowIndex]; int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
//因为点击编辑后,该cell变为textbox,所以用该方法取值 string name = ((TextBox)(row.Cells[0].Controls[0])).Text; string score = ((TextBox)(row.Cells[2].Controls[0])).Text.Trim();
//获取checkbox值
int ismember = ((CheckBox)row.Cells[3].Controls[0]).Checked?1:0;
using (SqlConnection sqlcon = new SqlConnection(DBHelper.con))
{
SqlDataReader dr;
string sql = "Update student Set name='" + name + "',score='" + score + "',member=" +ismember+" Where ID=" + ID + "";
SqlCommand myCommand = new SqlCommand(sql, sqlcon);
sqlcon.Open();
dr = myCommand.ExecuteReader();
//获取或设置要编辑的行的索引。默认值为 -1,指示没有正在编辑的行 .取消编辑状态。
//将gridview从编辑模式切换成浏览模式
GridView1.EditIndex = -1;
sqlcon.Close();
}
DataBindings();
}
//绑定每一行时执行
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Header和Footer:e.Row.RowIndex =-1
if (e.Row.RowIndex >= 0 )
{
if(e.Row.RowState==DataControlRowState.Normal ||e.Row.RowState==DataControlRowState.Alternate )
{
sum += Convert.ToInt32(e.Row.Cells[2].Text);
}
}
//求某一列的值合计
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = "合计:";
e.Row.Cells[2].Text = sum.ToString();
}
//绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
//为单元格添加属性
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("OnClick", "javascript: return confirm('你确认要删除\"" + e.Row.Cells[0].Text.Trim() + "\"吗?')");
//鼠标经过时,行背景色变
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'");
//鼠标移出时,行背景色变
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#DEDFDE'");
}
}
}
//勾选“全选”checkbox
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
foreach(GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
//根据ID选中gridview中的checkbox,该checkbox使用的是模板
((CheckBox)row.FindControl("CheckBox1")).Checked = CheckAll.Checked;
}
}
}
//点击“插入”按钮
protected void LinkButton1_Click(object sender, EventArgs e)
{
string name = this.txtname.Text;
string score = this.txtscore.Text;
int ismember = this.CheckBox2.Checked ? 1 : 0;
using (SqlConnection sqlcon = new SqlConnection(DBHelper.con))
{
SqlDataReader dr;
string sql = "insert into student (name,member,score) values('" + name + "'," + ismember + "," + score + ")";
SqlCommand myCommand = new SqlCommand(sql, sqlcon);
sqlcon.Open();
dr = myCommand.ExecuteReader();
//获取或设置要编辑的行的索引。默认值为 -1,指示没有正在编辑的行 .取消编辑状态。
//将gridview从编辑模式切换成浏览模式
sqlcon.Close();
}
DataBindings();
}
}
前台代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="IDU1.aspx.cs" Inherits="capital2_IDU1" Title="Untitled Page" %>
<!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 id="Head1" runat="server">
<title>无标题页</title>
<script type="text/javascript">
function DeleteEmpty(str)
{
var s=str.toString();
return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}
function LoadCheck()
{
var name=DeleteEmpty(document.getElementById('<%=txtname.ClientID %>').value);
var score1=DeleteEmpty(document.getElementById('<%=txtscore.ClientID %>').value);
if(name=="")
{
document.getElementById("Name").innerHTML="please enter a name";
}
else if(score1=="")
{
document.getElementById("Score").innerHTML="please enter a score";
}
else
{
__doPostBack('link','');
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" Height="152px" Width="572px" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound" ShowFooter="True" DataKeyNames="id">
<Columns>
<asp:BoundField DataField="name" HeaderText="姓名" />
<asp:BoundField DataField="id" HeaderText="编号" DataFormatString="{0:000#}" ReadOnly="True" />
<asp:BoundField DataField="score" HeaderText="分数" />
<asp:CheckBoxField DataField="member" HeaderText="是否会员" >
<ItemStyle HorizontalAlign="Center" />
</asp:CheckBoxField>
<asp:TemplateField HeaderText="选择">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"/>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:CommandField EditText="编辑" HeaderText="编辑" ShowEditButton="True" />
<asp:CommandField DeleteText="删除" HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<FooterStyle BackColor="Silver" ForeColor="Black" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
</asp:GridView>
<asp:CheckBox ID="CheckAll" runat="server" OnCheckedChanged="CheckBox2_CheckedChanged" Text="全选" AutoPostBack="True" />
<table style="width: 572px" id="Table1">
<tr>
<td style="width: 74px">
Name:</td>
<td style="width: 382px">
<asp:TextBox ID="txtname" runat="server"></asp:TextBox><span id="Name"><font color="red"></font></span>
</td>
</tr>
<tr>
<td style="width: 74px">
Score:</td>
<td style="width: 382px">
<asp:TextBox ID="txtscore" runat="server"></asp:TextBox>
<span id="Score"><font color="red"></font></span>
</td>
</tr>
<tr>
<td style="width: 74px; height: 22px">
Member:</td>
<td style="width: 382px; height: 22px">
<asp:CheckBox ID="CheckBox2" runat="server" /></td>
</tr>
<tr>
<td style="width: 74px; height: 22px" colspan="2">
<input id="BtInsert" type="button" value="插入" language="javascript" onclick="LoadCheck();"/></td>
</tr>
</table>
</div>
</form>
</body>
</html>
4、鼠标移到GridView某一行时改变该行的背景色方法
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
if(e.Row.RowState==DataControlRowState.Normal|| e.Row.RowState==DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("OnClick", "javascript: return confirm('你确认要删除\"" + e.Row.Cells[0].Text.Trim() + "\"吗?')");
//鼠标经过时,行背景色变 e.Row.Attributes.Add("onmouseover","this.style.backgroundColor='#E6F5FA'"); //鼠标移出时,行背景色变 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#DEDFDE'");
}
}
}
5、GridView实现删除时弹出确认对话框
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
if(e.Row.RowState==DataControlRowState.Normal|| e.Row.RowState==DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("OnClick", "javascript: return confirm('你确认要删除\"" + e.Row.Cells[0].Text.Trim() + "\"吗?')");
//鼠标经过时,行背景色变
e.Row.Attributes.Add("onmouseover","this.style.backgroundColor='#E6F5FA'");
//鼠标移出时,行背景色变
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#DEDFDE'");
}
}
}
6、GridView实现自动编号
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowIndex != -1) { int id = e.Row.RowIndex + 1; e.Row.Cells[0].Text = id.ToString(); } }
注意:该编号只是当前页中的编号。