当前位置:  编程技术>.net/c#/asp.net

GridView 新增、删除及编辑范例代码

    来源: 互联网  发布时间:2014-08-30

    本文导语:  asp.net gridview新增、删除与编辑。 1、Asp.Net页面   代码示例:     gridview             function checkDel(str)         {             if(!confirm("确认删除 "+str+" 吗?"))                 return(false);      ...

asp.net gridview新增、删除与编辑。

1、Asp.Net页面
 

代码示例:




    gridview
   
        function checkDel(str)
        {
            if(!confirm("确认删除 "+str+" 吗?"))
                return(false);
        }
   


   
   

   
        
           
               
               
                   
                       
                   
                   
                       
                   
               
              
               
                   
                       
                   
                   
                       
                   
               
              
               
                   
                       
                   
                   
                       
                   
               
              
               
                   
                       
                   
                   
                       
                   
               
              
               
                   
                       
                   
               
           
           
           
           
           
           
           
           
       
       
       

   

2、后台代码
 

代码示例:

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;

public partial class GridViewAdd : System.Web.UI.Page
{
    SqlHelper sqlHelper = new SqlHelper();
    private static DataTable dtUser;

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
            bindData(true);
        this.BtSave.Enabled = false;
    }

    ///
    /// 数据绑定
    ///
    ///
    private void bindData(bool refresh)
    {

        if (refresh || dtUser == null)
        {
            DataSet ds = sqlHelper.getDs("Select * from MyUser", CommandType.Text, null, "MyUser");
            dtUser = ds.Tables[0];
        }

        this.myGridView.DataSource = dtUser.DefaultView;
        this.myGridView.DataBind();
    }

    ///
    /// 删除
    ///
    ///
    ///
    public void txtDel_Click(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(((LinkButton)sender).CommandArgument);

        //从数据库中删除
        string Sql;
        Sql = "Delete from MyUser where ID=" + id;
        sqlHelper.ExecuteSql(Sql,CommandType.Text,null);

        //从内存中删除
        DataRow[] dr = dtUser.Select("ID=" + id);
        if(dr.Length > 0)
            dtUser.Rows.Remove(dr[0]);
        this.bindData(false);
    }

    ///
    /// 新增
    ///
    ///
    ///
    protected void BtAdd_Click(object sender, EventArgs e)
    {
        DataRow row = dtUser.NewRow();
        row["ID"] = (int)getMaxIdInTable(dtUser, "ID") + 1;
        row["BirthDay"] = DateTime.Now;
        dtUser.Rows.Add(row);

        this.myGridView.EditIndex = dtUser.Rows.Count - 1;
        this.bindData(false);
        this.BtSave.Enabled = true;
    }

    ///
    /// 保存
    ///
    ///
    ///
    protected void BtSave_Click(object sender, EventArgs e)
    {
        int i = this.myGridView.EditIndex;
        string userName = ((TextBox)this.myGridView.Rows[i].FindControl("txtUserName")).Text.ToString();
        string password = ((TextBox)this.myGridView.Rows[i].FindControl("txtPassword")).Text.ToString();
        string describe = ((TextBox)this.myGridView.Rows[i].FindControl("txtDescribe")).Text.ToString();
        DateTime birthDay = ((Calendar)this.myGridView.Rows[i].FindControl("txtBirthDay")).SelectedDate;

        string Sql;
        Sql = "Insert Into MyUser(UserName,Password,Describe,BirthDay) values('" + userName + "','" + password + "','" + describe + "','" + birthDay + "')";
        sqlHelper.ExecuteSql(Sql, CommandType.Text, null);
        this.myGridView.EditIndex = -1;
        this.bindData(true);
        this.BtSave.Enabled = false;

    }

    ///
    /// 得到指定表中关键字的最大值
    ///
    ///
    ///
    ///
    private object getMaxIdInTable(DataTable table, string keyID)
    {
        if (table.Rows.Count == 0)
            return 0;
        DataView dv = new DataView();
        dv.Table = table;
        dv.Sort = keyID + " Desc";
        return dv[0][keyID];
    }

    ///
    /// 用户取消事件
    ///
    ///
    ///
    protected void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        this.myGridView.EditIndex = -1;
        this.bindData(true);
    }

    ///
    /// 用户更新事件
    ///
    ///
    ///
    protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int i = this.myGridView.EditIndex;
        if (dtUser.Rows[i].RowState == DataRowState.Added)
        {
            BtSave_Click(sender, e);
            dtUser.Rows[i].AcceptChanges();
        }
        else
        { //表示修改
            int id = Convert.ToInt16(this.myGridView.Rows[i].Cells[1].Text);
            string userName = ((TextBox)this.myGridView.Rows[i].FindControl("txtUserName")).Text.ToString();
            string password = ((TextBox)this.myGridView.Rows[i].FindControl("txtPassword")).Text.ToString();
            string describe = ((TextBox)this.myGridView.Rows[i].FindControl("txtDescribe")).Text.ToString();
            DateTime birthDay = ((Calendar)this.myGridView.Rows[i].FindControl("txtBirthDay")).SelectedDate;

            string Sql;
            Sql = "Update MyUser Set UserName='" + userName + "',Password='" + password + "',Describe='" + describe + "',BirthDay='" + birthDay + "' where id=" + id;
            sqlHelper.ExecuteSql(Sql, CommandType.Text, null);
            this.myGridView.EditIndex = -1;
            this.bindData(true);
            this.BtSave.Enabled = false;
        }
    }

    ///
    /// 用户删除事件
    ///
    ///
    ///
    protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int selectIndex = e.RowIndex;
      
        //这里的 Cells[1] 对应的是编号列
        int id = Convert.ToInt16(this.myGridView.Rows[selectIndex].Cells[1].Text);

        string Sql;
        Sql = "Delete from MyUser where ID=" + id;
        sqlHelper.ExecuteSql(Sql,CommandType.Text,null);

        //从内存中删除
        DataRow[] dr = dtUser.Select("ID=" + id);
        dtUser.Rows.Remove(dr[0]);
        this.bindData(false);
    }

    ///
    /// 用户编辑事件
    ///
    ///
    ///
    protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.myGridView.EditIndex = e.NewEditIndex;
        this.bindData(false);
    }

    protected void myGridView_DataBound(object sender, EventArgs e)
    {
        string userName = "";
        foreach (GridViewRow r in this.myGridView.Rows)
        {
            //userName = ((Label)r.FindControl("showUserName")).Text;
            ((LinkButton)r.FindControl("txtDel")).Attributes.Add("onclick", "return checkDel(" + userName + ")");
        }
    }
}

3、数据访问类
 

代码示例:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
public class SqlHelper
    {
        private const string ConnStr = "Data Source=127.0.0.1;Initial Catalog=HJ;User id=sa;Password=as;";
        private SqlConnection Conn = null;
        private SqlCommand Cmd = null;
        private SqlDataAdapter Adp = null;
        private DataSet ds = new DataSet();

        ///
        /// 返回 DataSet
        ///
        ///
        ///
        ///
        ///
        public DataSet getDs(string cmdText, CommandType cmdType, SqlParameter[] pars, string tableName)
        {
            Conn = new SqlConnection(ConnStr);
            Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.CommandText = cmdText;
            Cmd.CommandType = cmdType;
            if (pars != null)
            {
                foreach (SqlParameter par in pars)
                {
                    Cmd.Parameters.Add(par);
                }
            }

            Adp = new SqlDataAdapter(Cmd);

            try
            {
                Conn.Open();
                if (tableName == null || tableName == string.Empty)
                    Adp.Fill(ds);
                else
                    Adp.Fill(ds, tableName);
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                Conn.Close();
            }
            return ds;
        }

        ///
        /// 执行Sql语句,返回受影响的行数
        ///
        ///
        ///
        ///
        ///
        public int ExecuteSql(string cmdText, CommandType cmdType, SqlParameter[] pars)
        {
            int res = 0;
            Conn = new SqlConnection(ConnStr);
            Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.CommandText = cmdText;
            Cmd.CommandType = cmdType;
            if (pars != null)
            {
                foreach (SqlParameter par in pars)
                {
                    Cmd.Parameters.Add(par);
                }
            }

            try
            {
                Conn.Open();
                res = Cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                Conn.Close();
            }
            return res;
        }

        ///
        /// 返回 DataReader 对象
        ///
        ///
        ///
        ///
        ///
        public SqlDataReader getDr(string cmdText, CommandType cmdType, SqlParameter[] pars)
        {
            SqlDataReader dr = null;

            Conn = new SqlConnection(ConnStr);
            Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.CommandText = cmdText;
            Cmd.CommandType = cmdType;
            if (pars != null)
            {
                foreach (SqlParameter par in pars)
                {
                    Cmd.Parameters.Add(par);
                }
            }

            try
            {
                Conn.Open();
                dr = Cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
            }
            return dr;
        }

        public object getScalar(string cmdText, CommandType cmdType, SqlParameter[] pars)
        {
            object res = null;

            Conn = new SqlConnection(ConnStr);
            Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.CommandText = cmdText;
            Cmd.CommandType = cmdType;
            if (pars != null)
            {
                foreach (SqlParameter par in pars)
                {
                    Cmd.Parameters.Add(par);
                }
            }

            try
            {
                Conn.Open();
                res = Cmd.ExecuteScalar();
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                Conn.Close();
            }
            return res;
        }
    }

4、数据库表
 

代码示例:

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MyUser]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[MyUser]
GO

CREATE TABLE [dbo].[MyUser] (
 [ID] [int] IDENTITY (1, 1) NOT NULL ,
 [UserName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
 [Password] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
 [Describe] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
 [BirthDay] [datetime] NULL
) ON [PRIMARY]
GO


    
 
 
 
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • 利用sender的Parent获取GridView中的当前行(获取gridview的值)
  • DevExpress实现GridView当无数据行时提示消息
  • GridView添加滚动条的二种方法
  • 编辑gridview的小例子
  • GridView控件列上格式化时间的用法举例
  • 为GridView添加复选框的方法
  • asp.net MVC进阶学习---HtmlHelper之GridView控件拓展(一)
  • gridview更新时获取不到textbox中新值的解决方法
  • Asp.net设置GridView自适应列宽的实现代码
  • gridview的buttonfield获取该行的索引值(实例讲解)
  • c#获取gridview的值代码分享
  • asp.net GridView删除对话框的二个方法
  • C#使用RenderControl将GridView控件导出到EXCEL的方法
  • GridView动态添加列的实现代码
  • GridView生成的HTML代码示例对比
  • asp.net GridView用法笔记
  • GridView控件事件详细解析
  • asp.net遍历文件夹下所有子文件夹并绑定到gridview上的方法
  • Android之ScrollView嵌套ListView和GridView冲突的解决方法
  • gridview 行选添加颜色和事件


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3