asp.net中使用DatagridView的增删改方法具体实现_实用技巧

default.aspx 页面:

复制代码 代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GPS_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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <!--GridView中必须写的几个事件:onrowediting、onrowupdating、onrowcancelingedit、onrowdeleting--->
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            onpageindexchanging="GridView1_PageIndexChanging" onrowcancelingedit="GridView1_RowCancelingEdit"
            onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
            onrowdeleting="GridView1_RowDeleting"
            onselectedindexchanging="GridView1_SelectedIndexChanging">
            <Columns>
                <asp:TemplateField HeaderText="编号" Visible="False">
                    <ItemTemplate>
                        <asp:Label ID="lblNum" runat="server" Text='<%# Eval("Num") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="姓名">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtTableName" runat="server" Text='<%# Eval("TableName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Eval("TableName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="地址">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtTextName" runat="server" Text='<%# Eval("TextName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Eval("TextName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField HeaderText="状态" ShowSelectButton="True" />
                <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
                <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
            </Columns>
        </asp:GridView>

        <br />
               
        <asp:Button ID="btnAdd" runat="server" onclick="btnAdd_Click" Text="添加" />
        <br />
        <br />   
    </div>
    </form>
</body>
</html>

default.aspx.cs页面代码:

复制代码 代码如下:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using GPS_Web.ywpages.DAL;
using System.Data;
namespace GPS_Web
{
    /// <summary>
    /// 参考的网址:http://blog.csdn.net/wanglei_samrtfish/article/details/8070480
    /// </summary>
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridViewBind();
            }
        }
        private void GridViewBind()
        {
            string sql = "select Num,TableName,TextName from dbo.GroupType_Demo";
            try
            {     //绑定数据源
                GridView1.DataSource = SqlHelper.ExecuteDataset(SqlHelper.GetConnSting(), CommandType.Text, sql).Tables[0];
                GridView1.DataBind();
            }
            catch (Exception ex){}
        }
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            GridViewBind();
        }
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            GridViewBind();
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {  //gridview编辑项索引等于单击行的索引
            GridView1.EditIndex = e.NewEditIndex;
            GridViewBind();
        }
        /// <summary>
        /// 修改事件
        /// </summary>
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {  //取出编号
            int Num = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("lblNum")).Text.ToString());
            //获取修改的值的内容
            string TableName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtTableName")).Text;
            string TextName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtTextName")).Text;
            //更新记录
            string sql = string.Format("update dbo.GroupType_Demo set TableName='{0}',TextName='{1}' where Num={2}",TableName,TextName,Num);
            try
            {
                int i = SqlHelper.ExecuteNonQuery(SqlHelper.GetConnSting(), CommandType.Text, sql);
                if (i > 0)
                {
                    ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script language='javascript'>alert('修改成功!')</script>");
                }
                else
                {
                    ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script language='javascript'>alert('修改失败!')</script>");
                }
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script language='javascript'>alert('操作无效!')</script>");
            }
            GridView1.EditIndex = -1;
            GridViewBind();
        }
        /// <summary>
        /// 删除事件
        /// </summary>
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //取出编号
            int Num = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("lblNum")).Text.ToString());
            //更新记录
            string sql = string.Format("delete dbo.GroupType_Demo where num={0}", Num);
            try
            {
                int i = SqlHelper.ExecuteNonQuery(SqlHelper.GetConnSting(), CommandType.Text, sql);
                if (i > 0)
                {
                    ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script language='javascript'>alert('删除成功!')</script>");
                }
                else
                {
                    ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script language='javascript'>alert('删除失败!')</script>");
                }
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script language='javascript'>alert('操作无效!')</script>");
            }  www.jb51.net
            GridView1.EditIndex = -1;
            GridViewBind();
        }
        /// <summary>
        /// 添加按钮
        /// </summary>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Default_Add.aspx");
        }
        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            //行号
            int i = e.NewSelectedIndex;
            GridViewRow row = GridView1.Rows[e.NewSelectedIndex];

            btnAdd.Text = "你选中了第" + (i+1) + "行。";
        }       
    }
}

执行后的页面效果:

时间: 2024-12-10 01:19:49

asp.net中使用DatagridView的增删改方法具体实现_实用技巧的相关文章

Asp.net中时间格式化的6种方法详细总结_实用技巧

1. 数据控件绑定时格式化日期方法: 复制代码 代码如下: <asp:BoundColumn DataField="AddTime" HeaderText="添加时间" DataFormatString="{0:yyyy-MM-dd HH:mm}></asp:BoundColumn> <asp:BoundField DataField="AddTime" HeaderText="添加时间"

ASP.NET中实现定制自己的委托和事件参数类_实用技巧

本文实例讲述了ASP.NET中实现定制自己的委托和事件参数类的方法,对于学习ASP.NET有很好的参考借鉴价值.具体方法如下: 一般在实际开发中,对于事件不需要传递数据信息时,像上面的KingTextBox控件的事件,在引发事件时传递的参数为EventArgs.Empty,如下所示: OnTextChanged(EventArgs.Empty); 这是因为控件KingTextBox的TextChanged事件比较简单,这里不需要参数对象传递数据.但像一些复杂的控件比如GridView的按钮命令事

ASP.NET中MVC传递数据的几种形式总结_实用技巧

本文实例讲述了ASP.NET中MVC传递数据的几种形式.分享给大家供大家参考.具体如下: 在Asp.net mvc开发中,Controller需要向View提供Model,然后View将此Model渲染成HTML.这篇文章介绍三种由Controller向View传递数据的方式,实现一个DropDownList的显示. 第一种:ViewData ViewData是一个Dictionary.使用非常简单,看下面代码: public ActionResult ViewDataWay(int id) {

ASP.NET中实现jQuery Validation-Engine的Ajax验证实现代码_实用技巧

见下图: 验证的例子:http://www.position-relative.net/creation/formValidator/ 官方地址: http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/ 这个插件支持大部分的浏览器,但由于有使用到了css3的阴影和圆角样式,所以在IE浏览器下无法看到圆角和阴影效果(IE 9 支持圆角效果). 本文主要内容是

asp.net中javascript的引用(直接引入和间接引入)_实用技巧

Asp.net 中引入Javascript 的方法有很多.在做牛腩的时候主要讲了两种. 个人认为可以分为直接引入,和间接引入. 一.直接引入.在前台页面调用自定义的javascript 函数: 1.打开前台页面在 head 元素之间加入 script 元素,将 type 元素设置为 " text/javascript ".然后写javascript自定义的函数. 复制代码 代码如下: <head runat="server"> <script ty

增加asp.net应用程序性能的20种方法(简单有效)_实用技巧

1.禁用session假如您用不到session会话跟踪请务必禁用它.您可以在每个asp.net页面中设置如下:<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication1.WebForm1" EnableSessionState="false" %>

.net中使用DatagridView的增删改方法

 default.aspx 页面: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GPS_Web.Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http

ASP.NET中使用Application对象实现简单在线人数统计功能_实用技巧

注:最近在复习ASP.NET,为了加深印象,会制作一些小的demo程序,分享给大家. 1 新建ASP.NET网站,编辑Global.asax文件,修改后的文件内容如下所示. <%@ Application Language="C#" %> <script runat="server"> void Application_Start(object sender, EventArgs e) { // 在应用程序启动时运行的代码 Applicati

asp.net中Fine Uploader文件上传组件使用介绍_实用技巧

最近在处理后台数据时需要实现文件上传.考虑到对浏览器适配上采用Fine Uploader. Fine Uploader 采用ajax方式实现对文件上传.同时在浏览器中直接支持文件拖拽[对浏览器版本有要求类似IE版本必须是9或是更高的IE10].在不同浏览器中提供统一用户体验.该组件基本覆盖目前所有主流浏览器.同时没有任何第三方组件依赖.相当Clear.在服务器端已经覆盖支持了ASP.NET/ColdFusion/Java/Node.js/Perl/PHP/Python. 对上传细节类似限制文件大