手工绑定数据到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();
}
}

}
}

时间: 2025-01-05 12:01:59

手工绑定数据到GridView的相关文章

GridView等表格模板列绑定数据的方法

//绑定GridView每一行中的CheckBoxList protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { CheckBoxList cbl = (CheckBoxList)e.Row.FindControl("ckbCheckBox"); if (cbl != null) {

在aspx页动态加载ascx页面内容,给GridView控件绑定数据

在aspx页动态加载ascx页面内容 //加载ascx页面内容Control c1 = this.Page.LoadControl("WebUserControl1.ascx");//绑定到aspx页的PlaceHolder控件上PlaceHolder1.Controls.Add(c1); DataSet ds = SqlServerHelpr.GetDataSet("select * from dbo.Table_1");//给GridView控件绑定数据Grid

ASP.NET——GridView控件绑定数据

        ASP.NET提供了许多种数据服务器控件,用于在Web页面中显示数据库中的表数据,GridView控件就是其中之一.这个控件和我们以前学过的DataGridView控件几乎是一样的,所以对GridView控件我们也并不陌生,下面简单介绍一下它的使用.         前台: 在工具箱中找到GridView控件,并把它拖拽到代码编辑区域.   第一步,进入设计界面,在GridView控件上方有一个向右的黑色小三角,单击这个按钮,选择编辑列,如图:          第二步,去掉自动

集合绑定数据

使用 ObservableCollection 列表控件主要是 ListBox.ListView.GridView 等. 为列表控件绑定数据不再是为 DataContext 属性赋值,应该使用列表控件自有的ItemsSource属性. 当列表数据元素由 ItemsSource绑定,就不能再动态操作(增删改) Items 属性 数据模板:

ASPxGridView中如何对主从表绑定数据

注:在从表的aspxgridview中的(OnDataBinding()事件中绑定数据)-----代码如下 //绑定属性值表protected void grid2_sonTable_DataBinding(object sender, EventArgs e){ASPxGridView songrid = (ASPxGridView)sender; //实例化从表表object _faterid = songrid.GetMasterRowKeyValue(); //获取主表行id(模板gri

ASP.NET编辑与更新数据(非GridView控件实现)

Insus.NET在实现<ASP.NET开发,从二层至三层,至面向对象 (5)>http://www.cnblogs.com/insus/p/3880606.html 中,没有把数据编辑与更新功能一起演示,留下给网友们自由发挥,但是还是有网友想看看Insus.NET用实现方法. 以前Insus.NET的做法,是在GridView控件中进行.如这篇视频教程<GridView Edit Update Cancel Delete>http://www.cnblogs.com/insus/

WPF ListView点击删除某一行并获取绑定数据

最近在开发WPF程序时遇到一个问题,在gridview中希望实现在每一行最后添加一个删除的按钮,但是发现点击每行的button时只会触发button的点击事件,并没有选中这一行,此时调用list.SelectedItem时无法得到对应的绑定数据. UI.xaml<ListView x:Name="list" Height="494" Width="1121" FontSize="16" ><ListView.

关于angularJS绑定数据时自动转义html标签

折磨了两天,最后发现答案竟如此简单,不过辛苦还是值得的,毕竟为了弄明白这一点又学习了更多代码. angularJS在进行数据绑定时默认是会以文本的形式输出,也就是对你数据中的html标签不进行转义照单全收,这样提高了安全性,防止了html标签中的注入攻击,但有些时候还是需要的,特别是从数据库读取带格式的文本时,无法正常的显示在页面中. 而要对html进行转义,则要在数据绑定的html标签中使用ng-bind-html属性,该属性依赖与$sanitize,也就是需要引入angular-saniti

[Devexpress]GridControl 绑定DataSource时GridView列不变化

Devexpress  GridControl 绑定DataSource时GridView列不变化 1.使用VS自带的DataGridView替代 2.数据绑定以后调用 gridView.PopulateColumns()  函数 重新创建列 gcSummary.DataSource = _dtData; gvSummary.PopulateColumns();