GridView 做增删改查操作

前台代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>
    
        用户名:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        密码:<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
 <asp:Button ID="btnAdd" runat="server" Height="25px" οnclick="btnAdd_Click" 
            Text="添加" Width="82px" />
        <br />
                
        <asp:TextBox ID="txtUser" runat="server"></asp:TextBox>
 <asp:Button ID="btnSeek" runat="server" Height="21px" οnclick="btnSeek_Click" 
            Text="查询" Width="86px" />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            onrowdeleting="GridView1_RowDeleting" Width="527px" 
            onrowdatabound="GridView1_RowDataBound" 
            onrowediting="GridView1_RowEditing" 
            onrowcancelingedit="GridView1_RowCancelingEdit" 
            onrowupdating="GridView1_RowUpdating">
            <Columns>
                <asp:TemplateField HeaderText="编号">
                    <%--<EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("id") %>'></asp:TextBox>
                    </EditItemTemplate>--%>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="用户名">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" MaxLength="20" Width="80" runat="server" Text='<%# Bind("userName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("userName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="密码">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox3" MaxLength="20" Width="80" runat="server" Text='<%# Bind("userPassword") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("userPassword") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="管理" ShowHeader="False">
                    <EditItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" 
                            CommandName="Update" Text="更新"></asp:LinkButton>
                         <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" 
                            CommandName="Cancel" Text="取消"></asp:LinkButton>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" 
                            CommandName="Edit" Text="编辑"></asp:LinkButton>
                         <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" 
                            CommandName="Delete" Text="删除"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public partial class _Default : System.Web.UI.Page
{
    string sqlstr=ConfigurationManager.ConnectionStrings["sqlstr"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetData();
        }
        
    }
    private void GetData()
    {
        using (SqlConnection sqlcnn=new SqlConnection(sqlstr))
        {
            using (SqlCommand sqlcmm=sqlcnn.CreateCommand())
            {
                sqlcmm.CommandText = "select * from Users";
                DataTable dt = new DataTable();
                SqlDataAdapter adapter = new SqlDataAdapter(sqlcmm);
                adapter.Fill(dt);
                this.GridView1.DataSource = dt;
                this.GridView1.DataBind();
            }
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        using (SqlConnection sqlcnn=new SqlConnection(sqlstr))
        {
            using (SqlCommand sqlcmm=sqlcnn.CreateCommand())
            {
                sqlcmm.CommandText = "insert into users(userName,userPassword)values(@userName,@password)";
                sqlcmm.Parameters.AddWithValue("@userName",this.txtName.Text);
                sqlcmm.Parameters.AddWithValue("@password",this.txtPassword.Text);
                sqlcnn.Open();
                int i= sqlcmm.ExecuteNonQuery();
                if (i > 0)
                {
                    Response.Write("<script>alert('添加成功!')</script>");
                    GetData();
                }
                else
                {


                    Response.Write("<script>alert('添加失败!')</script>");
                }
            }
        }
    }//向数据库添加数据


    protected void btnSeek_Click(object sender, EventArgs e)
    {
        using (SqlConnection sqlcnn = new SqlConnection(sqlstr))
        {
            using (SqlCommand sqlcmm = sqlcnn.CreateCommand())
            {
                sqlcmm.CommandText = "select * from users where username=@username";
                sqlcmm.Parameters.AddWithValue("@userName",this.txtUser.Text);
                sqlcnn.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(sqlcmm);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                this.GridView1.DataSource = dt;
                this.GridView1.DataBind();
               // GetData();
                
            }
        }
    }//查询数据
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
       
      int index = e.RowIndex;//获取当前行的索引
      int id=Convert.ToInt32((this.GridView1.Rows[index].FindControl("Label1") as Label).Text);
      using (SqlConnection sqlcnn=new SqlConnection(sqlstr))
      {
          using (SqlCommand sqlcmm=sqlcnn.CreateCommand())
          {
              sqlcmm.CommandText = "delete from users where id=@id";
              sqlcmm.Parameters.AddWithValue("@id",id);
              sqlcnn.Open();
              int i= sqlcmm.ExecuteNonQuery();
              if (i>0)
              {
                  Response.Write("<script>alert('删除成功!')</script>");
                  GetData();
              }
              else
              {
                  Response.Write("<script>alert('删除失败!')</script>");
              }
      
          }
      }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType==DataControlRowType.DataRow)
        {
            LinkButton lb = e.Row.FindControl("LinkButton2") as LinkButton;
            if (lb.Text=="删除")
            {
                 lb.Attributes.Add("onclick","return confirm('确定要删除这一行吗?')");
            }
           
        }
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        GetData();
    }//处于编辑状态
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        GetData();
    }//取消编辑
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string username=(GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox).Text;
        string password=(GridView1.Rows[e.RowIndex].FindControl("TextBox3") as TextBox).Text;
        if (username == string.Empty || password == string.Empty)
        {
            Response.Write("<script>alert('用户名或密码不能为空!')</script>");
        }
        else
        {
            using (SqlConnection sqlcnn = new SqlConnection(sqlstr))
            {
                using (SqlCommand sqlcmm = sqlcnn.CreateCommand())
                {
                    sqlcmm.CommandText = "update Users set userName=@username,userPassword=@password where id=@id";
                    sqlcmm.Parameters.AddWithValue("@username", username);
                    sqlcmm.Parameters.AddWithValue("@password", password);
                    sqlcmm.Parameters.AddWithValue("@id", Convert.ToInt32((GridView1.Rows[e.RowIndex].FindControl("Label1") as Label).Text));
                    sqlcnn.Open();
                    int i = sqlcmm.ExecuteNonQuery();
                    if (i > 0)
                    {
                        Response.Write("<script>alert('更新成功!')</script>");
                        GridView1.EditIndex = -1;
                        GetData();
                    }
                    else
                    {
                        Response.Write("<script>alert('更新失败!')</script>");
                    }
                }
           }
        }
    }//更新操作
}

点击此链接下载源码和数据库

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值