GridView的绑定,添加,删除,更改;

17 篇文章 0 订阅

GridView的绑定,添加,删除,更改;
在用GridView控件时候的操作如下
用的的数据库如下在这里插入图片描述

接下来是gridview的使用
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
前台代码如下

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="False" Height="177px" Width="1056px" DataKeyNames="id" OnRowCancelingEdit="gvStudent_RowCancelingEdit" OnRowDeleting="gvStudent_RowDeleting" OnRowEditing="gvStudent_RowEditing" OnRowUpdating="gvStudent_RowUpdating" OnSelectedIndexChanged="gvStudent_SelectedIndexChanged" >
                <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:BoundField DataField="Name" HeaderText="姓名" />
                    <asp:BoundField DataField="Sex" HeaderText="性别" />
                    <asp:BoundField DataField="Age" HeaderText="年龄" />
                    <asp:BoundField DataField="Address" HeaderText="地址" />
                    <asp:CommandField ShowDeleteButton="True" />
                    <asp:CommandField ShowEditButton="True" />
                </Columns>
            </asp:GridView>
        </div>
        <br />
        <br />
        <div>
            姓名:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
            性别:<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
            年龄:<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox><br />
            地址:<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox><br />
            <asp:Button ID="btnSubmit" runat="server" Text="添加" OnClick="btnSubmit_Click" />
        </div>
    </form>
</body>
</html>

后台代码如下

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
/*
 绑定
1.数据库位置
2.数据库连接通道
3.找到表的位置,根据通道
4.创建数据集
5.把找到的表,放到数据集
6.将数据集放到数据源
7.将数据源绑定

添加
Button
1.获取要添加的内容
2.数据库位置
3.数据库连接通道
4.将获取要添加的内容添加到表里,根据通道
5.打开数据库
6.获取受影响行数
7.关闭数据库
8.判断是否成功
9.弹窗告诉是否成功
 



删除
删除事件
放入ID
1.数据库位置
2.数据库连接通道
3.获取受影响行数的id
4.SQL语句
5.将删除SQL语句放到表里,根据通道
5.打开数据库
6.获取受影响行数
7.关闭数据库
8.判断是否成功
9.弹窗告诉是否成功
 */
/*
 SqlConnection  数据库连接对象
 SqlDataAdapter   数据填充器(数据适配器)
 DataSet        数据集(内存的表的集合)
 DataSource    数据源
 DataBind      数据绑定
 SqlCommand  数据库执行语句
 * ExecuteNonQuery获取受影响行数
 
选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
 */
public partial class GridviewUserInfo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            StudentBind();
        }
    }
    /// <summary>
    /// GridView的数据绑定;
    /// </summary>
      //Student是数据库的名字
      string connStr = "Data Source=.;Initial Catalog=Student;Integrated Security=True";
    public void StudentBind()
    {
        SqlConnection conn = new SqlConnection(connStr);//数据库的连接对象;
        string sql = "select * from StudentInfos";//sql语句从数据库里面查询数据;
        SqlDataAdapter sda = new SqlDataAdapter(sql,conn);//数据填充器;
        DataSet ds = new DataSet();//建立数据存放的容器
        sda.Fill(ds);//将数据放入到容器里面;
        gvStudent.DataSource = ds;//数据源
        gvStudent.DataBind();//数据的绑定;
    }


    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //首先去掉前后的空格;Trim();
        string names = TextBox2.Text.Trim();
        string gender = TextBox3.Text.Trim();
        string ages = TextBox4.Text.Trim();
        string address1 = TextBox5.Text.Trim();
        SqlConnection conn = new SqlConnection(connStr);
        string sql = "insert into StudentInfos values('" + names + "','" + gender + "','" + ages + "','" + address1 + "')";
        SqlCommand cmd = new SqlCommand(sql, conn);
        conn.Open();
        int flag = cmd.ExecuteNonQuery();//获取受影响的行数;
        conn.Close();
        if (flag > 0)
        {
            StudentBind();
            Response.Write("<script>alert('添加成功')</script>");
           
        }
        else
        {
            Response.Write("<script>alert('添加失败')</script>");
            
        }
    }

  



    protected void gvStudent_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        //这是指获取GridView1控件的第“e.RowIndex+1”行的第2列单元格内的第一个控件
        //e.RowIndex是指当前鼠标选中的行的序号,+1是因为数组的下标从0开始,0表示第1,1实际表示第2了
        string names =( (TextBox)(this.gvStudent.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
        string gender = ((TextBox)(this.gvStudent.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
        string ages = ((TextBox)(this.gvStudent.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
        string address1 = ((TextBox)(this.gvStudent.Rows[e.RowIndex].Cells[4].Controls[0])).Text;
        //取出当前操作行的DataKeys对应的Names的ID
        int id = Convert.ToInt32(gvStudent.DataKeys[e.RowIndex]["id"]);
        string sql = "update StudentInfos set Name='" + names+ "',Sex='" + gender+ "',Age='" + ages+ "',Address='" + address1+"'where Id='"+id+"'";
        SqlConnection conn = new SqlConnection(connStr);
        SqlCommand sda = new SqlCommand(sql, conn);
        conn.Open();
        int flag = sda.ExecuteNonQuery();
        conn.Close();
        if (flag > 0)
        {
            StudentBind();
            Response.Write("<script>alert('编辑成功')</script>");
            gvStudent.EditIndex = -1;
        }
        else
        {
            Response.Write("<script>alert('编辑失败')</script>");
        }
    }

    protected void gvStudent_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //把当前编辑的索引,赋给控件的编辑索引,(让编辑的行显示出来)
        gvStudent.EditIndex = e.NewEditIndex;
        //绑定
        StudentBind();
    }

    protected void gvStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        //获取编辑行的id值
        int id = Convert.ToInt32(gvStudent.DataKeys[e.RowIndex]["id"]);
        SqlConnection conn = new SqlConnection(connStr);
        string sql = "delete from StudentInfos where Id='" + id + "'";
        SqlCommand cmd = new SqlCommand(sql, conn);
        conn.Open();
        int flag = cmd.ExecuteNonQuery();
        conn.Close();
        if (flag > 0)
        {
            StudentBind();
            Response.Write("<script>alert('删除成功')</script>");
        }
        else
        {
            Response.Write("<script>alert('删除失败')</script>");
        }

    }

    protected void gvStudent_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //让编辑行的索引退回去
        gvStudent.EditIndex = -1;
        //绑定
        StudentBind();
    }

    protected void gvStudent_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}

结果如下
在这里插入图片描述

  • 9
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Dev控件中的GridView是一个强大的表格控件,可以用于展示数据以及对数据进行修改、删除添加等操作。 要直接修改GridView中的数据,可以按照以下步骤进行: 1. 将GridView的Editable属性设置为True,以启用编辑模式。 2. 在GridView的事件处理程序中,处理需要修改的行的编辑事件。例如,如果需要编辑第二行,可以在GridView的RowEditing事件中添加以下代码: ``` protected void gridView_RowEditing(object sender, GridViewEditEventArgs e) { gridView.EditIndex = e.NewEditIndex; // 绑定数据源 BindData(); } ``` 3. 在GridView的事件处理程序中,处理需要保存修改后的数据的行的更新事件。例如,如果需要保存第二行的修改,可以在GridView的RowUpdating事件中添加以下代码: ``` protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e) { // 获取需要更新的行的数据 string id = gridView.DataKeys[e.RowIndex].Value.ToString(); string name = ((TextBox)gridView.Rows[e.RowIndex].FindControl("txtName")).Text; string age = ((TextBox)gridView.Rows[e.RowIndex].FindControl("txtAge")).Text; // 更新数据 // ... // 取消编辑模式 gridView.EditIndex = -1; // 绑定数据源 BindData(); } ``` 4. 在GridView的事件处理程序中,处理需要取消修改的行的取消事件。例如,如果需要取消修改第二行的数据,可以在GridView的RowCancelingEdit事件中添加以下代码: ``` protected void gridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { // 取消编辑模式 gridView.EditIndex = -1; // 绑定数据源 BindData(); } ``` 这样,就可以直接在GridView中修改数据了。当然,还需要根据实际情况进行适当的修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值