手工绑定数据到GridView

手工绑定数据到GridView,并实现增、删、查、改,取消功能,切记:一定要在GridView
属性的“DataKeyNames”项中增加一个索引字段,如userid等,否则运行时会提示超出索引范围!!
----------------------------------------------------------------------------------------

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="web.Default" %>

<!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>ado.net Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" Width="100%" AllowPaging="True" PageSize="6" OnPageIndexChanging="GridView1_PageIndexChanging" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" DataKeyNames="userid">
<Columns>
<asp:BoundField DataField="userid" HeaderText="用户编码"/>
<asp:BoundField DataField="username" HeaderText="用户姓名"/>
<asp:BoundField DataField="userpwd" HeaderText="用户密码"/>
<asp:BoundField Datafield="Ename" HeaderText="用户昵称"/>
<asp:BoundField DataField="Email" HeaderText="注册邮箱"/>
<asp:BoundField DataField="usertype" HeaderText="用户类型"/>
<asp:BoundField DataField="chengwei" HeaderText="用户称谓"/>
<asp:BoundField Datafield="r_datetime" HeaderText="注册时间"/>
<asp:CommandField HeaderText="修改" ShowEditButton="True" />

<asp:TemplateField HeaderText="删除" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" CommandName="Delete" Text="删除" OnClientClick="return confirm('您确定要删除这行记录吗?')">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

<asp:CommandField HeaderText="添加" ShowInsertButton="True" />
<asp:CommandField HeaderText="选择" ShowSelectButton="True" />
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
&nbsp;&nbsp;<br />
<br />
<hr />
<br />
<br />
&nbsp; &nbsp; &nbsp;&nbsp;
<asp:Label ID="Label1" runat="server" Text="用户类型"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;

<asp:Label ID="Label2" runat="server" Text="用户姓名"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;
<br />
<br />
<br />
&nbsp; &nbsp; &nbsp;&nbsp;
<asp:Label ID="Label3" runat="server" Text="用户密码"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;

<asp:Label ID="Label4" runat="server" Text="用户昵称"></asp:Label>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;
<br />
<br />
<br />
&nbsp; &nbsp; &nbsp;&nbsp;
<asp:Label ID="Label5" runat="server" Text="用户邮箱"></asp:Label>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox><br />
<br />
<br />
<hr />
<br />
<asp:Button ID="Button1" runat="server" Text="增加记录" OnClick="Button1_Click" />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;
<asp:Button ID="Button2" runat="server" Text="点击转到GridViewTable表单" OnClick="Button2_Click"/>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="链接到传值表单" />
</div>
</form>
</body>
</html>

--------------------------------------------------------------------------------------------

 

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;

namespace web
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindData();//调用下面已经封装好的数据绑定函数
}
}
public void bindData()//将绑定数据的代码封装为bindData()函数
{
DataAccess.Class1 dac = new DataAccess.Class1();
DataSet ds = dac.getUsers();
this.GridView1.DataSource = ds.Tables[0].DefaultView;
this.GridView1.DataBind();

}

protected void Button1_Click(object sender, EventArgs e)
{
//方法一
//DataAccess.Class1 dac = new DataAccess.Class1();
//string sql = "Insert into users(usertype,userName,userpwd,Ename,Email) values('"+this.TextBox1.Text+"','"+this.TextBox2.Text+"','"+this.TextBox3.Text+"','"+this.TextBox4.Text+"','"+this.TextBox5.Text+"')";
//dac.ExecuteSql(sql);


//方法二
DataAccess.Class1 dac = new DataAccess.Class1();
DataSet ds = dac.getUsers();
DataRow dr = ds.Tables[0].NewRow();

//类似以下五行可代码可反复使用
dr["usertype"] = this.TextBox1.Text;
dr["userName"] = this.TextBox2.Text;
dr["userpwd"] = this.TextBox3.Text;
dr["Ename"] = this.TextBox4.Text;
dr["Email"] = this.TextBox5.Text;
ds.Tables[0].Rows.Add(dr);

//以下5行为直接存贮数据,右边存入左边
//dr["usertype"] = "aaa";
//dr["userName"] = "bbb";
//dr["userpwd"] = "ccc";
//dr["Ename"] = "ddd";
//dr["Email"] = "eee";

//调用业务层的一个方法
//dac.updateUsers(ds);//方法一:调用普通参数
dac.updateUsersByStoredProcedure(ds);//方法二:调用存贮过程

bindData(); //绑定数据到表单
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.GridView1.PageIndex = e.NewPageIndex;

bindData();
}

protected void Button2_Click(object sender, EventArgs e)
{
Server.Transfer("Testuser.aspx");
}

protected void Button3_Click(object sender, EventArgs e)
{
Server.Transfer("web1.aspx");
}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
this.GridView1.EditIndex = e.NewEditIndex;
bindData();

}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.GridView1.EditIndex = -1;
bindData();
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SqlConnection conn = new SqlConnection("Server=localhost;database=Test;uid=abc;pwd=manager");

SqlCommand cmd = new SqlCommand("delete users where userid='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'", conn);
conn.Open();
try
{
int i = Convert.ToInt32(cmd.ExecuteNonQuery());
if (i > 0)
{
Response.Write("<script language=javascript>alert('删除成功!')</script>");
}
else
{
Response.Write("<script language=javascript>alert('删除失败!')</script>");
}
bindData();
}
catch (Exception erro)
{
Response.Write("错误信息:" + erro.Message);
}
finally
{
conn.Close();
}
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString().Trim();
string pwd = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString().Trim();
string en= ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString().Trim();
string mail = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString().Trim();
string type = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString().Trim();
string datetimes = ((TextBox)GridView1.Rows[e.RowIndex].Cells[7].Controls[0]).Text.ToString().Trim();

SqlConnection conn = new SqlConnection("Server=localhost;database=Test;uid=abc;pwd=manager");
SqlCommand cmd = new SqlCommand("update users set username='" + name + "' , userpwd='" + pwd + "' , ename='" + en + "' , email='" + mail + "' , usertype='" + type + "',r_datetime='" + datetimes + "' where userid='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'", conn);
conn.Open();
try
{
int i = Convert.ToInt32(cmd.ExecuteNonQuery());
if (i > 0)
{
Response.Write("<script language=javascript>alert('保存成功!')</script>");
}
else
{
Response.Write("<script language=javascript>alert('保存失败!')</script>");
}
GridView1.EditIndex = -1;
bindData();
}
catch (Exception erro)
{
Response.Write("错误信息:" + erro.Message);
}
finally
{
conn.Close();
}
}


}
}

 

posted on 2015-01-24 15:19  微风~  阅读(388)  评论(0编辑  收藏  举报