初学ASP.NET不久自己动手做了个GridView简单的例子(感谢爱追逐的小猪、等等网络朋友)
VS2005下调试成功(个人感觉不错 遗憾的是界面不美观)。
主要目的是学习GridView控件。
表结构如下:
--创建student表
create table student
(
stuID int identity(1,1) primary key, --学号(只是为了方便)
stuName varchar(10) not null, --姓名
stuSex varchar(2) not null, --性别
stuAge int , --年龄
stuAddress varchar(200) --家庭地址
)
default2.aspx前台代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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>GridView使用例子</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" DataKeyNames="stuID" runat="server" AllowPaging="True"
AutoGenerateColumns="False"
EmptyDataText="没有记录"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating"
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="GridView1_RowDataBound"
EditRowStyle-BackColor="#ebebeb">
<Columns>
<asp:TemplateField HeaderText="选择">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Text=" " Width="24px" Font-Size="10" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="stuID" HeaderText="学号" ItemStyle-Font-Size="10" ReadOnly="True"/>
<asp:BoundField DataField="stuName" HeaderText="姓名" ItemStyle-Font-Size="10" ControlStyle-Width="50px"/>
<asp:BoundField DataField="stuAge" HeaderText="年龄" ItemStyle-Font-Size="10" ControlStyle-Width ="20px" />
<asp:TemplateField HeaderText="性别">
<ItemTemplate>
<asp:Label ID="Label1" Font-Size ="10" runat="server" Text='<%# Bind("stuSex", "{0}") %>' Width="56px"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="RadioButtonList1" Font-Size="10" runat="server" SelectedValue='<%# Bind("stuSex", "{0}") %>'>
<asp:ListItem>男</asp:ListItem>
<asp:ListItem>女</asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="stuAddress" HeaderText="地址" ItemStyle-Font-Size="10" />
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="全部选中" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="删除所选" OnClick="Button2_Click" OnClientClick="return confirm('真的要删除选中的项目吗?');" /><br />
</div>
</form>
</body>
</html>
default2.aspx.cs后台代码如下:
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;
using
System.Drawing;
//
要使用颜色,引入命名空间
public
partial
class
Default2 : System.Web.UI.Page

...
{
protected void Page_Load(object sender, EventArgs e)

...{

if (!IsPostBack)

...{
BindGrid();
}
}

protected void BindGrid()

...{
this.GridView1.DataSource =GetStudentData().Tables["student"];
this.GridView1.DataBind();
}

private DataSet GetStudentData()

...{
string strConn;
string strSql;
strSql = "select *from student";
strConn = "server=.;database=tempdb;uid=sa;pwd=;";
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter myCommand = new SqlDataAdapter(strSql, conn);
myCommand.SelectCommand.CommandType = CommandType.Text;
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "student");
conn.Close();
return myDataSet;
}


//-------------------------------------------------------------------------------------
//项目全选或者取消全选
protected void Button1_Click(object sender, EventArgs e)

...{
if (this.Button1.Text == "全部选中")

...{
foreach (GridViewRow row in GridView1.Rows)

...{
CheckBox box1=(CheckBox)row.Cells[0].FindControl("CheckBox1");
box1.Checked = true;
}
this.Button1.Text ="全部取消";
}
else

...{
foreach (GridViewRow row in GridView1.Rows)

...{
CheckBox box1 = (CheckBox)row.Cells[0].FindControl("CheckBox1");
box1.Checked = false;
}

this.Button1.Text = "全部选中";
}

}

//删除所选记录
protected void Button2_Click(object sender, EventArgs e)

...{
SqlConnection conn = new SqlConnection("server=.;database=tempdb;uid=sa;pwd=;");
foreach(GridViewRow row in GridView1.Rows)

...{
CheckBox box1 = (CheckBox)row.Cells[0].FindControl("CheckBox1");
if (box1.Checked == true)

...{

string strCmd;
strCmd = "delete from student where stuID=" + Int64.Parse(row.Cells[1].Text);

SqlCommand cmd = new SqlCommand(strCmd,conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
this.Button1.Text="全部选中";
BindGrid();
}
//------------------------------------------------------------------------------------------------------



//---------------------------------------------------------------------------------------------
//编辑选中的某行记录
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

...{
this.Button1.Text = "全部选中";
GridView1.Columns[0].Visible = false;
GridView1.EditIndex=(int)e.NewEditIndex; //设置要编辑的行
BindGrid();
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

...{
//string stuIdName = GridView1.DataKeyNames[0]; //获取主键名
//Response.Write(stuId);

int stuId = int.Parse(GridView1.Rows[e.RowIndex].Cells[1].Text); //获取学生学号(主键),第二列,下标从0开始。
string stuName = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text; //获取学生姓名
int stuAge = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);

//获取GridView表格中的数据
// 正常状态下((LiteralControl)GridView1.Rows[e.RowIndex].Cells[4].FindControl("Label1")).Text
//
//编辑状态下((RadioButtonList)GridView1.Rows[e.RowIndex].Cells[4].FindControl("RadioButtonList1")).SelectedValue;
// ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string stuSex = ((RadioButtonList)GridView1.Rows[e.RowIndex].Cells[4].FindControl("RadioButtonList1")).SelectedValue;
string stuAddress = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
string strUpSql = "update student set stuname='" + stuName + "',stuAge=" + stuAge + ",stuSex='" + stuSex + "',stuAddress='" + stuAddress + "' where stuId=" + stuId;

string strConn;
string strSql;
strConn = "server=.;database=tempdb;uid=sa;pwd=;";
SqlConnection conn = new SqlConnection(strConn);
SqlCommand myCommand = new SqlCommand(strUpSql, conn);
myCommand.CommandType = CommandType.Text;
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
conn.Dispose();
GridView1.Columns[0].Visible = true; //显示选择列
GridView1.EditIndex = -1;
BindGrid();
}

//取消更新
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

...{
this.Button1.Text = "全部选中";
GridView1.Columns[0].Visible = true; //显示选择列
GridView1.EditIndex = -1;
BindGrid();

}
//----------------------------------------------------------------------------------------------


//------------------------------------------
//分页功能
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

...{
this.Button1.Text = "全部选中";
GridView1.PageIndex = e.NewPageIndex;
//Response.Write(GridView1.PageIndex); //显示当前页编号
BindGrid();
}
//------------------------------------


//鼠标变色事件
//此方法没有显示预期的效果,原因查找中

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

...{
if (e.Row.RowType == DataControlRowType.DataRow) //判断是否是DataRow,以防止鼠标经过Header也有效果

...{

e.Row.Attributes.Add("onMouseover", "c=this.style.backgroundcolor;this.style.backgroundcolor='#ff6699'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundcolor=c");

}
}

}
