ASP。NET中GridView控件的事件使用实例 下载本文

ASP.NET中GridView控件的事件使用实例

在学习ASP.NET一段时间后,对GridView控件的事件进行了分析了解,下面以一个示例进行演示:

本演示只涉及控件事件,数据库连接不在这里阐述。 新建一个Web窗体,命名为test 两个文件内容如下: test.aspx文件:

<%@ Page Language=\ AutoEventWireup=\ CodeFile=\ Inherits=\ %>


test

onrowediting=\ OnRowCancelingEdit=\ onrowupdating=\

test.aspx.cs文件如下:

using System;

using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI;

using System.Web.UI.WebControls; using System.Data;

using System.Data.SqlClient;

public partial class test : System.Web.UI.Page {

DBClass dbobj = new DBClass();

protected void Page_Load(object sender, EventArgs e) {

if(!IsPostBack) DataBound(); }

protected void DataBound() {

string strSql = \教¨?师o|表à¨a\; DataTable dsTable = dbobj.GetDataSetStr(strSql, \); GridView1.DataSource = dsTable;

GridView1.DataKeyNames = new string[] { \工?è号?\ }; //主??键¨1

GridView1.DataBind(); }

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) {

Label1.Text = \你?选?择?的ì?是o?:êo\ + GridView1.SelectedRow.Cells[5].Text; }

protected void GridView1_RowDeleting(object sender,GridViewDeleteEventArgs e) {

Label1.Text = \你?选?择?的ì?是o?:êodelete\;

string uid = GridView1.DataKeys[e.RowIndex].Value.ToString();

string strSql = \教¨?师o|表à¨a where 工?è号?='\+uid+\;

SqlConnection con = dbobj.GetConnection(); SqlCommand comm = new SqlCommand(strSql,con); dbobj.ExecNonQuery(comm); DataBound();

}

protected void GridView1_RowEditing(object sender,GridViewEditEventArgs e) {

GridView1.EditIndex = e.NewEditIndex; //为aGridView1制?定?§编ਤ辑-行D的ì?索??引°y Label1.Text = \你?选?择?的ì?是o?:êoedit\; DataBound(); }

protected void GridView1_RowCancelingEdit(object sender,GridViewCancelEditEventArgs e) {

GridView1.EditIndex = -1;//设|¨¨置?编ਤ辑-行D索??引°y为a-1,ê?即??没?有?D编ਤ辑-行D Label1.Text = \你?取¨?消?了¢?edit\; DataBound(); }

protected void GridView1_RowUpdating(object sender,GridViewUpdateEventArgs e) {

Label1.Text = \你?选?择?的ì?是o?:êoupdate\;

string uid = GridView1.DataKeys[e.RowIndex].Value.ToString();

GridViewRow row = GridView1.Rows[e.RowIndex];

TextBox tb1,tb2,tb3;

tb1 = (TextBox)(row.Cells[3].Controls[0]); tb2 = (TextBox)(row.Cells[4].Controls[0]); tb3 = (TextBox)(row.Cells[5].Controls[0]);

string strSql = \教¨?师o|表à¨a set 姓?名?='\+tb2.Text+\性?别àe='\+tb3.Text+\工?è号?='\+uid+\;

SqlConnection conn = dbobj.GetConnection(); SqlCommand mycmd = new SqlCommand(strSql,conn); dbobj.ExecNonQuery(mycmd); GridView1.EditIndex = -1; DataBound(); } }

在此测试页面中可以实现使用GridView控件的命令按钮选择一行,使用GridView控件的命令按钮修改数据,使用GridView控件的命令按钮删除数据。

Word文档下载:ASP。NET中GridView控件的事件使用实例.doc
搜索更多:ASP。NET中GridView控件的事件使用实例


最新浏览