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

GridView 主从表编辑与新增范例代码

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

    本文导语:  asp.net中gridview主从表编辑与新增的例子,主要有两个页面: 1、PastList.aspx  主表列表页面 2、PastView.aspx 主从表编辑页面 SqlHelper.cs   数据访问类 一个实体类 一个枚举类 1、主表列表页面 PastList.aspx   代码示例:    ...

asp.net中gridview主从表编辑与新增的例子,主要有两个页面:
1、PastList.aspx  主表列表页面
2、PastView.aspx 主从表编辑页面
SqlHelper.cs   数据访问类
一个实体类
一个枚举类

1、主表列表页面 PastList.aspx
 

代码示例:




    主从表新增和编辑的测试


   
   

   
       
           
           
           
               
                    编辑
               
           
       
       
       
       
       
       
       
       
   
       
       

   


 

1)、后台代码
 

代码示例:

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 PartList : System.Web.UI.Page
{
    SqlHelper sqlHelper = new SqlHelper();
    private static DataTable dtType;

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

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

        if (refresh || dtType == null)
        {
            DataSet ds = sqlHelper.getDs("Select * from BigType order by TypeOrder", CommandType.Text, null, "BigType");
            dtType = ds.Tables[0];
        }

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

    ///
    /// 新增
    ///
    ///
    ///
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("PartView.aspx");
    }
}

2、主从表编辑页面 PartView.aspx
 

代码示例:




    主从表新增和编辑的测试
   
        function checkFrm()
        {
            if(document.form1.txtBigTypeName.value.length==0)
            {
                alert("请输入类别名称");
                document.form1.txtBigTypeName.focus();
                return(false);
            }
            if(isNaN(document.form1.txtTypeOrder.value) || document.form1.txtTypeOrder.value.length==0)
            {
                alert("请输入数字");
                document.form1.txtTypeOrder.focus();
                return(false);
            }
        }
        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;
using System.Data.SqlClient;
public partial class PartView : System.Web.UI.Page
{
    private int BigTypeID;
    private string Sql;
    SqlHelper sqlHelper = new SqlHelper();
    private static DataTable dtSmallType = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        this.BtSave.Attributes.Add("onclick", "return checkFrm();");
        if (!Page.IsPostBack)
        {
            BigTypeID = Convert.ToInt32(Request.QueryString["id"]);
            this.hidID.Text = BigTypeID.ToString();

            if (BigTypeID != 0)
            {//表示修改状态
                bindBigType();
                bindData(true);
            }
            else
            {//新增时,把架构给dtSmallType
                fillTable();
            }
        }
        else
        {
            BigTypeID = Convert.ToInt32(this.hidID.Text);
        }
    }

    ///
    /// 取从表的架构给 dtSmallType
    ///
    private void fillTable()
    {
        Sql = "Select * from SmallType where 1=0";
        dtSmallType = sqlHelper.getDs(Sql, CommandType.Text, null, "SmallType").Tables[0];
    }

    ///
    /// 绑定主表
    ///
    private void bindBigType()
    {
        Sql = "Select * from BigType where ID=" + BigTypeID;
        SqlDataReader dr;
        dr = sqlHelper.getDr(Sql, CommandType.Text, null);

        while (dr.Read())
        {
            this.txtBigTypeName.Text = dr["BigTypeName"].ToString();
            this.txtBigTypeDescribe.Text = dr["BigTypeDescribe"].ToString();
            this.txtTypeOrder.Text = dr["TypeOrder"].ToString();
        }
    }

    ///
    /// 数据绑定,并且判断从表记录是否从数据库中从新读取
    ///
    ///
    private void bindData(bool refresh)
    {
        //绑定从表数据
        if (refresh || dtSmallType == null)
        {
            Sql = "Select * from SmallType where BigTypeID=" + BigTypeID;
            dtSmallType = sqlHelper.getDs(Sql, CommandType.Text, null, "SmallType").Tables[0];
        }

        this.detailGridView.DataSource = dtSmallType.DefaultView;
        this.detailGridView.DataBind();
    }

    ///
    /// 新增从表记录
    ///
    ///
    ///
    protected void BtAdd_Click(object sender, EventArgs e)
    {
        DataRow row = dtSmallType.NewRow();
        row["ID"] = (int)getMaxIdInTable(dtSmallType, "ID") + 1;

        if (this.BigTypeID != 0)
        { //表示修改主从记录
            row["BigTypeID"] = BigTypeID;
        }
        dtSmallType.Rows.Add(row);

        this.detailGridView.EditIndex = dtSmallType.Rows.Count - 1;
        this.bindData(false);
    }

    ///
    /// 保存主表修改
    ///
    ///
    ///
    protected void BtSave_Click(object sender, EventArgs e)
    {
        if (this.detailGridView.EditIndex > -1)
        {
            Response.Write("alert('请先结束从表编辑');");
            return;
        }

        BigTypeEntity entity = new BigTypeEntity();
        entity.BigTypeName     = this.txtBigTypeName.Text.ToString();
        entity.BigTypeDescribe = this.txtBigTypeDescribe.Text.ToString();
        entity.TypeOrder       = Convert.ToInt16(this.txtTypeOrder.Text);

        if (BigTypeID != 0)
        { //表示修改
            entity.ID = BigTypeID;
            sqlHelper.SaveBigTypeAndSmallType(entity, dtSmallType, EditMethod.Update);
        }
        else
        {//表示新增
            sqlHelper.SaveBigTypeAndSmallType(entity, dtSmallType, EditMethod.Insert);
            BigTypeID = (int)sqlHelper.getScalar("Select Top 1 ID from BigType Order By ID Desc", CommandType.Text, null);
            this.hidID.Text = BigTypeID.ToString();
        }

        this.bindData(true);
    }

    ///
    /// GridView编辑事件
    ///
    ///
    ///
    protected void detailGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.detailGridView.EditIndex = e.NewEditIndex;
        this.bindData(false);
    }

    ///
    /// GridView撤消事件
    ///
    ///
    ///
    protected void detailGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        this.detailGridView.EditIndex = -1;
        this.bindData(false);
    }

    ///
    /// GridView更新事件
    ///
    ///
    ///
    protected void detailGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //保存在本地
        int i = this.detailGridView.EditIndex;
      
        string typeName = ((TextBox)this.detailGridView.Rows[i].FindControl("txtSmallTypeName")).Text.ToString();
        string typeDescribe = ((TextBox)this.detailGridView.Rows[i].FindControl("txtSmallTypeDescribe")).Text.ToString();
        int typeOrder = Convert.ToInt16(((TextBox)this.detailGridView.Rows[i].FindControl("txtSmallTypeOrder")).Text);
        dtSmallType.Rows[i]["SmallTypeName"] = typeName;
        dtSmallType.Rows[i]["SmallTypeDescribe"] = typeDescribe;
        dtSmallType.Rows[i]["SmallTypeOrder"] = typeOrder;

        this.detailGridView.EditIndex = -1;
        this.bindData(false);
    }

    ///
    /// GridView删除事件
    ///
    ///
    ///
    protected void detailGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int selectIndex = e.RowIndex;

        //这里的 Cells[0] 对应的是编号列
        int id = Convert.ToInt16(this.detailGridView.Rows[selectIndex].Cells[0].Text);

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

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

        this.bindData(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 detailGridView_DataBound(object sender, EventArgs e)
    {
      
    }
}

3、数据库访问类 SqlHelper.cs
 

代码示例:

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;
        }

        ///
        /// 只为主从表保存测试使用
        ///
        /// 主表实体
        /// 从表的Table,包含状态
        /// 方法,是否新增或者修改
        public void SaveBigTypeAndSmallType(BigTypeEntity entity, DataTable dtSmallType, EditMethod method)
        {
            int BigTypeID;
            string Sql;
            Conn = new SqlConnection(ConnStr);
            Cmd = new SqlCommand();
            Cmd.CommandType = CommandType.Text;
            Cmd.Connection = Conn;

            Conn.Open();
            SqlTransaction tran = Conn.BeginTransaction();
            Cmd.Transaction = tran;

            try
            {
              
                if (method == EditMethod.Insert)
                {
                    //插入主表
                    Sql = "Insert Into BigType(BigTypeName,BigTypeDescribe,TypeOrder) values('" + entity.BigTypeName + "','" + entity.BigTypeDescribe + "'," + entity.TypeOrder + ")";
                    Cmd.CommandText = Sql;
                    Cmd.ExecuteNonQuery();

                    //取得刚才插入的 ID,如果主键是GUID,在这里处理就方便些
                    Cmd.CommandText = "Select Top 1 ID from BigType order By ID Desc";
                    BigTypeID = (int)Cmd.ExecuteScalar();

                    //插入从表
                    foreach (DataRow dr in dtSmallType.Rows)
                    {//新增状态下,从表所有行的DataRow属性都为Added
                        Sql = "Insert Into SmallType(SmallTypeName,SmallTypeDescribe,SmallTypeOrder,BigTypeID) ";
                        Sql += "values('" + dr["SmallTypeName"].ToString() + "','" + dr["SmallTypeDescribe"].ToString() + "'," + dr["SmallTypeOrder"].ToString() + "," + BigTypeID + ")";
                        Cmd.CommandText = Sql;
                        Cmd.ExecuteNonQuery();
                    }
                }
                else if (method == EditMethod.Update)
                {
                    //修改主表
                    Sql = "Update BigType Set BigTypeName='" + entity.BigTypeName + "',BigTypeDescribe='" + entity.BigTypeDescribe + "',TypeOrder=" + entity.TypeOrder + " where ID=" + entity.ID.ToString();
                    Cmd.CommandText = Sql;
                    Cmd.ExecuteNonQuery();

                    //插入从表
                    foreach (DataRow dr in dtSmallType.Rows)
                    {
                        if (dr.RowState == DataRowState.Added)
                        {
                            Sql = "Insert Into SmallType(SmallTypeName,SmallTypeDescribe,SmallTypeOrder,BigTypeID) ";
                            Sql += "values('" + dr["SmallTypeName"].ToString() + "','" + dr["SmallTypeDescribe"].ToString() + "'," + dr["SmallTypeOrder"].ToString() + "," + entity.ID.ToString() + ")";
                            Cmd.CommandText = Sql;
                            Cmd.ExecuteNonQuery();
                        }
                        else if (dr.RowState == DataRowState.Modified)
                        {
                            Sql = "Update SmallType Set SmallTypeName='" + dr["SmallTypeName"].ToString() + "',SmallTypeDescribe='" + dr["SmallTypeDescribe"].ToString() + "',";
                            Sql += "SmallTypeOrder=" + dr["SmallTypeOrder"].ToString() + " where ID=" + dr["ID"].ToString();
                            Cmd.CommandText = Sql;
                            Cmd.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                tran.Rollback();
                throw new Exception(e.ToString());
            }
            finally
            {
                tran.Commit();
                Conn.Close();
            }
        }
    }

4、实体类
 

代码示例:

public class BigTypeEntity
{
    private int _ID;

    private string _BigTypeName;

    private string _BigTypeDescribe;

    private int _TypeOrder;

    public int ID
    {
        get { return this._ID; }
        set { this._ID = value;}
    }

    public string BigTypeName
    {
        get { return this._BigTypeName; }
        set { this._BigTypeName = value; }
    }

    public string BigTypeDescribe
    {
        get { return this._BigTypeDescribe; }
        set { this._BigTypeDescribe = value; }
    }
    public int TypeOrder
    {
        get { return this._TypeOrder; }
        set { this._TypeOrder = value; }
    }
}

5、枚举
 

代码示例:
public enum EditMethod
{
    Insert,
    Update
}

6、使用的数据库表的脚本
 

代码示例:

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

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

CREATE TABLE [dbo].[BigType] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[BigTypeName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[BigTypeDescribe] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
[TypeOrder] [int] NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[SmallType] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[SmallTypeName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[SmallTypeOrder] [int] NULL ,
[SmallTypeDescribe] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[BigTypeID] [int] 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