GridView C#2.0(asp.net)

原创 2007年10月11日 17:58:00

最近在研究gridview实现多行插入,更新,保存,删除的问题;

现在出来了,和大家分享一下;其实也就是对DataTable的操作

谢谢;如果觉得好的话请留言,以后我将继续努力

表:表明aaa

字段 id 主键,自动增长

字段 AAA varchar类型;

字段 BBB varchar类型;

页面代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!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>
    <center>
        <asp:GridView ID="GridView1" runat="server" DataKeyNames="id" Style="position: relative" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting">
            <Columns>
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>
        </asp:GridView>
       
        <asp:Button ID="btnAdd" runat="server" Style="position: relative" Text="保存" OnClick="btnAdd_Click" /><br>
        &nbsp;</center>
    </div>
    </form>
</body>
</html>

C#类代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Data.SqlClient;
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;

public partial class Default3 : System.Web.UI.Page
{
    SqlConnection mysqlcon = new SqlConnection("server=.;database=lianxi;integrated security=SSPI");
    protected DataTable dt = new DataTable();
    protected DataRow dr;//声明行变量
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["Table"] == null)
            {
                dt = Tables();//得到DataTable的值
                Session["Table"] = dt;
            }
            else {
                dt=(DataTable)Session["Table"];
            }
            BindGridView();
        }
    }
    protected void BindGridView()
    {
        //将数据与GridView1进行绑定
        if (dt != null)
        {
            try
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
                GridView1.HeaderRow.Cells[2].Text = "工号";
                GridView1.HeaderRow.Cells[3].Text = "姓名";
                GridView1.HeaderRow.Cells[4].Text = "年龄";
            }
            catch (SqlException)
            {
                Response.Write("<script language='javascript'>alert('出错了!!!');</script>");
            }
        }
        else {
            Response.Write("没有你要的数据");
        }
    }

    protected DataTable Tables()
    {
        //将数据保存到DataTable中
        try
        {
            string sql = "select * from aaa";
            SqlDataAdapter da = new SqlDataAdapter(sql, mysqlcon);
            da.Fill(dt);
            dr = dt.NewRow();//为DataTable添加一行(空值 以实现添加功能)
            dt.Rows.Add(dr);
            Session["Table"] = dt;//将dt保存在session中
        }
        catch (SqlException)
        {
        }
        return dt;
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //点击编辑后执行
        GridView1.EditIndex = e.NewEditIndex;
        dt = (DataTable)Session["Table"];
        BindGridView();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //取消编辑时执行
        GridView1.EditIndex = -1;
        dt = (DataTable)Session["Table"];
        BindGridView();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //更新dt事执行
        if (e.RowIndex == (GridView1.Rows.Count - 1))//判断选定的行是不是页面中GridView的最后一行,当是最后一行是执行
        {
            //为dt添加一新行
            string aaa = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.Trim();
            string bbb = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.Trim();
            dt = (DataTable)Session["Table"];
            dt.Rows.RemoveAt(e.RowIndex);//删除空行
            dr = dt.NewRow();
            dr[1] = aaa;
            dr[2] = bbb;
            dt.Rows.Add(dr);
            dr = dt.NewRow();//在次为dt添加空行以实现页面再次添加新行
            dt.Rows.Add(dr);
            Session["Table"] = dt;
            GridView1.EditIndex = -1;
            BindGridView();

        }
        else {
            //更新dt中现有行事执行
            string aaa = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.Trim();
            string bbb = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.Trim();
            dt = (DataTable)Session["Table"];
            dr = dt.Rows[e.RowIndex];

            dr.BeginEdit();//开始更新
            dr[1] = aaa;
            dr[2] = bbb;
            dr.EndEdit();//结束更新

            Session["Table"] = dt;
            GridView1.EditIndex = -1;
            BindGridView();
        }
       
    }


    protected bool Executer(string sql)
    {
        //SQL执行语句,实现数据库的更新,添加,删除
        SqlCommand mysqlcom = new SqlCommand(sql,mysqlcon);
        try {
            mysqlcon.Open();
            mysqlcom.ExecuteNonQuery();
            return true;
        }
        catch (SqlException) {
            return false;
        }
        finally {
            mysqlcom.Dispose();
            mysqlcon.Close();
        }
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        //点击删除事执行
        dt = (DataTable)Session["Table"];
        if (e.RowIndex == (GridView1.Rows.Count - 1))//判断:当点击GridView中的最后一行时(最后一行是空值)不执行删除
        {
        }else if(GridView1.Rows[e.RowIndex].Cells[2].Text.Trim()!=null){
            if (Session["aaa_id"] != null)//当删除掉的数据是数据库中原有的数据时执行,将原有数据的id保存到session中
            {
                Session["aaa_id"] += GridView1.Rows[e.RowIndex].Cells[2].Text.Trim();
            }
            else {
                Session["aaa_id"] = GridView1.Rows[e.RowIndex].Cells[2].Text.Trim();
            }
            dt.Rows.RemoveAt(e.RowIndex);
            Session["Table"] = dt;
            GridView1.EditIndex = -1;
            BindGridView();
        }
        else {
            //删除后来添加到dt中的数据(此时还未与数据库进行交互)
            dt.Rows.RemoveAt(e.RowIndex);
            Session["Table"] = dt;
            GridView1.EditIndex = -1;
            BindGridView();
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        dt = (DataTable)Session["Table"];
        foreach (DataRow drs in dt.Rows)
        {
            if (drs[0].ToString().Trim() != string.Empty)//判断dt中的id是否存在,如果存在则执行以下代码
            {
                //string id = drs["id"].ToString().Trim();
                //int i = int.Parse(id);
                //string aaa = drs["AAA"].ToString().Trim();
                //string bbb = drs["BBB"].ToString().Trim();
                string sql = string.Format("update aaa set AAA='" + drs["AAA"].ToString().Trim() + "',BBB='" + drs["BBB"].ToString().Trim() + "' where id=" + int.Parse(drs["id"].ToString().Trim()));
                Executer(sql);
            }
                //当dt中的id是空值是,判断后面的数据是否是空值,如为空值则不添加到数据库
            else if (drs[1].ToString() != string.Empty && drs[2].ToString() != string.Empty) 
            {
                //string aaa = drs[1].ToString();
                //string bbb = drs[2].ToString();
                string sql = "insert into aaa values('" + drs["AAA"].ToString().Trim() + "','" + drs["BBB"].ToString().Trim() + "')";
                Executer(sql);
            }
        }
        Session.Remove("Table");//保存完毕后则请空session["Table"]

        if (Session["aaa_id"] != null)
        {
            string aaa_id = Session["aaa_id"].ToString().Trim();//取出session["aaa_id"]的值
            for (int i = 0; i < aaa_id.Length; i++)
            {
                //将得到id的值
                int id = Convert.ToInt32(aaa_id.Substring(i,1));
                string sql = string.Format("delete aaa where id=" + id);//删除数据库中原有的数据
                Executer(sql);
            }
        }
        Session.Remove("aaa_id");//保存完毕后则请空session["aaa_id"]
        Response.Redirect("Default3.aspx");//跳转页面
    }
}

 

ASP.net GridView基本用法

转载自:http://www.cnblogs.com/ianunspace/p/3438233.html 包含有 数据的编辑,删除, 标题的添加,自定义分页,高亮显示鼠标所在,以及数据不足时...
  • riyuedangkong1
  • riyuedangkong1
  • 2017-05-19 17:18:32
  • 859

Asp.net中GridView使用详解(引)转

GridView无代码分页排序 GridView选中,编辑,取消,删除 GridView正反双向排序 GridView和下拉菜单DropDownList结合 GridView和CheckBox...
  • GUO_LOVER
  • GUO_LOVER
  • 2016-07-07 13:30:22
  • 1448

ASP.NET GridView做增删改查操作

  • 2012年04月15日 19:22
  • 304KB
  • 下载

asp.net 2.0 中GridView里设置日期格式

在asp.net 1.0 中的datagrid 中 设置日期字段格式时用 DataFormatString="{0:yyyy-MM-dd}"即可。   在gridview 中设置短日期格式 使用时不会...
  • 21aspnet
  • 21aspnet
  • 2007-03-19 19:46:00
  • 3956

【asp.net】GridView数据的编辑

·在新闻发布系统中,牛腩老师实现了点击编辑在表格中修改信息,使用的是Ajax,在总结GridView控件中突然发现了这个控件也有自带的编辑功能,于是研究了一段时间,虽然没有牛腩老师的方便和那样的效果,...
  • u012331102
  • u012331102
  • 2015-08-12 16:03:41
  • 806

asp.Net中Gridview动态创建模板列 .

Web中有时候数据源字段不确定,需要在绑定后添加新的字段,有没有方法了?方法是有的:之前也在网上搜索过,找到了一些方法,通过模板列可以实现。这里借鉴一下,自己亲自试验了一下,达到了想要的效果。 Gr...
  • LzShmily
  • LzShmily
  • 2013-02-05 15:22:39
  • 559

Asp.net Gridview合并单元格

View Code using System; using System.Collections.Generic; using System.Linq; using System.Web; ...
  • u012949335
  • u012949335
  • 2016-11-29 21:02:27
  • 1140

asp.net 4.0 gridview 增删改查

AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="10"             AutoG...
  • zxmz66
  • zxmz66
  • 2014-07-14 13:11:43
  • 801

asp.net 中利用GridView实现增加,修改,删除

1、创建数据库表SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[Table1...
  • emailqjc
  • emailqjc
  • 2010-10-31 12:17:00
  • 3253
收藏助手
不良信息举报
您举报文章:GridView C#2.0(asp.net)
举报原因:
原因补充:

(最多只允许输入30个字)