ASP.NET GridView:如何编辑和删除数据记录

时间:2016-04-24 18:20:49

标签: c# asp.net webforms aspxgridview

您好我使用gridview创建了一个表。 有没有办法实现编辑和删除。 我以前用PHP做过。我想要使​​用的方法是在表中再创建两列,每行包含编辑和删除按钮。然后,当单击按钮时,它会通过URL传递“id”并能够编辑或删除。不确定如何在asp.net webforms中执行此操作。下面是我的表格代码。谢谢。

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField HeaderText="Surgery" DataField="surgery" />
    <asp:BoundField HeaderText="PatientID" DataField="patientID" />
    <asp:BoundField HeaderText="Location" DataField="location" />

</Columns>          

SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);

conn.Close();

GridView1.DataSource = dt;
GridView1.DataBind();

4 个答案:

答案 0 :(得分:5)

GridView支持这些操作。您可以添加一个CommandField,其中包含命令按钮或LinkBut​​tons(您可以选择按钮类型并指定每个按钮的文本)。 patientID字段应包含在GridView的DataKeyNames属性中,以便在更新或删除数据库中的记录时检索它。

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
    DataKeyNames="patientID" 
    OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
    OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" >
<Columns>
    <asp:CommandField ShowEditButton="true" ShowCancelButton="true" ShowDeleteButton="true" />
    <asp:BoundField HeaderText="Surgery" DataField="surgery" />
    ...
</Columns>

然后,您需要在代码隐藏中处理一些事件:

// The RowEditing event is called when data editing has been requested by the user
// The EditIndex property should be set to the row index to enter edit mode
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    BindData();
}

// The RowCancelingEdit event is called when editing is canceled by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    BindData();
}

// The RowUpdating event is called when the Update command is selected by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    int patientID = (int)e.Keys["patientID"]
    string surgery = (string)e.NewValues["surgery"];
    string location = (string)e.NewValues["location"];

    // Update here the database record for the selected patientID

    GridView1.EditIndex = -1;
    BindData();
}

// The RowDeleting event is called when the Delete command is selected by the user
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int patientID = (int)e.Keys["patientID"]

    // Delete here the database record for the selected patientID

    BindData();
}

由于数据必须绑定到每个事件处理程序末尾的GridView,您可以在BindData实用程序函数中执行此操作,该函数也应该在页面最初加载时调用:

private void BindData()
{
    SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    conn.Close();
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindData();
    }
}

答案 1 :(得分:1)

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.test.app"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
     compile fileTree(include: ['*.jar'], dir: 'libs')
     testCompile 'junit:junit:4.12'

     compile 'com.android.support:appcompat-v7:23.4.0'
     compile 'com.android.support:design:23.4.0'
     compile 'com.android.support:cardview-v7:23.4.0'
     compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha2'
}

答案 2 :(得分:0)

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.Configuration;
using System.Data.SqlClient;

namespace FinalYearProject
{
    public partial class MBooking : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.BindGrid();
            }
        }

        private void BindGrid()
        {
            string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
                {
                    cmd.Parameters.AddWithValue("@Action", "SELECT");
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            GridView1.DataSource = dt;
                            GridView1.DataBind();
                        }
                    }
                }
            }
        }

        protected void Insert(object sender, EventArgs e)
        {
            string Username = txtUsername.Text;
            string Provincename = txtProvinceName.Text;
            string Cityname = txtCityname.Text;
            string Number = txtNumber.Text;
            string Name = txtName.Text;
            string ContentType = txtContentType.Text;
            string Data = txtData.Text;


            string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Action", "INSERT");
                    cmd.Parameters.AddWithValue("@Username", Username);
                    cmd.Parameters.AddWithValue("@Provincename ", Provincename);
                    cmd.Parameters.AddWithValue("@Cityname", Cityname);
                    cmd.Parameters.AddWithValue("@Number", Number);
                    cmd.Parameters.AddWithValue("@Name", Name);
                    cmd.Parameters.AddWithValue("@ContentType", ContentType);
                    //cmd.Parameters.AddWithValue("@Data", Data);
                    cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            this.BindGrid();
        }

        protected void OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            this.BindGrid();
        }

        protected void OnRowCancelingEdit(object sender, EventArgs e)
        {
            GridView1.EditIndex = -1;
            this.BindGrid();
        }

        protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = GridView1.Rows[e.RowIndex];
            int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
            string Username = (row.FindControl("txtUserName") as TextBox).Text;
            string Provincename = (row.FindControl("txtProvincename") as TextBox).Text;
            string Cityname = (row.FindControl("txtCityname") as TextBox).Text;
            string Number = (row.FindControl("txtNumber") as TextBox).Text;
            string Name = (row.FindControl("txtName") as TextBox).Text;
            string ContentType = (row.FindControl("txtContentType") as TextBox).Text;
            string Data = (row.FindControl("txtData") as TextBox).Text;
            string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Action", "UPDATE");
                    cmd.Parameters.AddWithValue("@BId", BId);
                    cmd.Parameters.AddWithValue("@Username", Username);
                    cmd.Parameters.AddWithValue("@Provincename ", Provincename);
                    cmd.Parameters.AddWithValue("@Cityname", Cityname);
                    cmd.Parameters.AddWithValue("@Number", Number);
                    cmd.Parameters.AddWithValue("@Name", Name);
                    cmd.Parameters.AddWithValue("@ContentType",ContentType) ;
                    cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
                    //cmd.Parameters.AddWithValue("@ContentType", SqlDbType.VarBinary, -1);
                    //cmd.Parameters.AddWithValue("@Data", SqlDbType.VarBinary, -1);

                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            GridView1.EditIndex = -1;
            this.BindGrid();
        }
        protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }

        protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
            //{
            //    (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
            //}
        }
        protected void DownloadFile(object sender, EventArgs e)
        {
            int id = int.Parse((sender as LinkButton).CommandArgument);
            byte[] bytes;
            string fileName, contentType;
            string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "select Name, Data, ContentType from tblbooking where BId=@BId";
                    cmd.Parameters.AddWithValue("@BId",id);
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        sdr.Read();
                        bytes = (byte[])sdr["Data"];
                        contentType = sdr["ContentType"].ToString();
                        fileName = sdr["Name"].ToString();
                    }
                    con.Close();
                }
            }
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = contentType;
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }

        protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
            string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Action", "DELETE");
                    cmd.Parameters.AddWithValue("@BId", BId);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            this.BindGrid();
        }
    }
}

答案 3 :(得分:0)

And Aspx page is:

<%@ Page Title="" Language="C#" MasterPageFile="~/admin.Master" AutoEventWireup="true" CodeBehind="MBooking.aspx.cs" Inherits="FinalYearProject.MBooking" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<style type="text/css">
               <%-- body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        table
        {
            border: 1px solid #ccc;
            border-collapse: collapse;
            background-color: #fff;
        }
        table th
        {
            background-color: #B8DBFD;
            color: #333;
            font-weight: bold;
        }
        table th, table td
        { background-color: #B8DBFD;
            padding: 5px;
            border: 1px solid #ccc;
        }
        table, table table td
        {
            border: 3px solid #ccc;
        }
  --%>
    .style1
    {
        width: 184px;
    }
    </style>

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  AllowPaging="True"
    OnPageIndexChanging="OnPageIndexChanging" PageSize="6" DataKeyNames="BId"
        OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
        OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" 
        EmptyDataText="No records has been added." 
        Style="margin:20px 0px 0px 25px;" BackColor="White" BorderColor="#3366CC" 
        BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="250px" 
        Width="1035px" >
        <Columns>
            <asp:TemplateField HeaderText="Username" ItemStyle-Width="120">
                <ItemTemplate>
                    <asp:Label ID="lblUsername" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtUsername"  style = "Width:100px;" runat="server" Text='<%# Eval("Username") %>'></asp:TextBox>
                </EditItemTemplate>

<ItemStyle Width="120px"></ItemStyle>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ProvinceName" ItemStyle-Width="120">
                <ItemTemplate>
                    <asp:Label ID="lblProvinceName" runat="server" Text='<%# Eval("Provincename") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtProvinceName"  style = "Width:100px;" runat="server" Text='<%# Eval("Provincename") %>'></asp:TextBox>
                </EditItemTemplate>

<ItemStyle Width="120px"></ItemStyle>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="CityName" ItemStyle-Width="120">
                <ItemTemplate>
                    <asp:Label ID="lblCityname" runat="server" Text='<%# Eval("Cityname") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtCityname"  style = "Width:100px;" runat="server" Text='<%# Eval("Cityname") %>'></asp:TextBox>
                </EditItemTemplate>

<ItemStyle Width="120px"></ItemStyle>
            </asp:TemplateField><asp:TemplateField HeaderText="Number" ItemStyle-Width="120">
                <ItemTemplate>
                    <asp:Label ID="lblNumber" runat="server" Text='<%# Eval("Number") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtNumber" style = "Width:100px;" runat="server" Text='<%# Eval("Number") %>'></asp:TextBox>
                </EditItemTemplate>

<ItemStyle Width="120px"></ItemStyle>
            </asp:TemplateField><asp:TemplateField HeaderText="Name" ItemStyle-Width="120">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtName" style = "Width:100px;" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
                </EditItemTemplate>

<ItemStyle Width="120px"></ItemStyle>
            </asp:TemplateField><asp:TemplateField HeaderText="ContentType" ItemStyle-Width="120">
                <ItemTemplate>
                    <asp:Label ID="lblContentType" runat="server" Text='<%# Eval("ContentType") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtContentType" style = "Width:100px;" runat="server" Text='<%# Eval("ContentType") %>'></asp:TextBox>
                </EditItemTemplate>

<ItemStyle Width="120px"></ItemStyle>
            </asp:TemplateField><asp:TemplateField HeaderText="Data" ItemStyle-Width="120">
                <ItemTemplate>
                    <asp:Label ID="lblData" runat="server" Text='<%# Eval("Data") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtData" style = "Width:100px;" runat="server" Text='<%# Eval("Data") %>'></asp:TextBox>
                </EditItemTemplate>

<ItemStyle Width="120px"></ItemStyle>
            </asp:TemplateField>
           <asp:TemplateField> <ItemTemplate>
                        <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
                            CommandArgument='<%# Eval("BId") %>'></asp:LinkButton>
                    </ItemTemplate></asp:TemplateField>
            <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
                ItemStyle-Width="100" >
<ItemStyle Width="100px"></ItemStyle>
            </asp:CommandField>
        </Columns>
        <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
        <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
        <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Center" 
            Font-Bold="True" Font-Italic="True" Font-Underline="True" Width="20px" />
        <RowStyle BackColor="White" ForeColor="#003399" />
        <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        <SortedAscendingCellStyle BackColor="#EDF6F6" />
        <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
        <SortedDescendingCellStyle BackColor="#D6DFDF" />
        <SortedDescendingHeaderStyle BackColor="#002876" />
    </asp:GridView>
    <br />

 <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse; margin:10px 0px 0px 25px;">
        <tr>
            <td style="width: 100px; background-color:#003399; color:#CCCCFF;">
              <b> Username:</b><br />
                <asp:TextBox ID="txtUsername" runat="server" Width="120" />
            </td>
            <td style="width: 100px;background-color:#003399; color:#CCCCFF;">
              <b> Provincename:</b><br />
                <asp:TextBox ID="txtProvinceName" runat="server" Width="120" />
            </td>
            <td style="width: 100px;background-color:#003399; color:#CCCCFF;">
               <b>Cityname:</b><br />
                <asp:TextBox ID="txtCityname" runat="server" Width="120" />
            </td>
            <td style="width: 100px;background-color:#003399; color:#CCCCFF;">
              <b> Number:</b><br />
                <asp:TextBox ID="txtNumber" runat="server" Width="120" />
            </td>
            <td style="width: 100px;background-color:#003399; color:#CCCCFF;">
              <b> Name:</b><br />
                <asp:TextBox ID="txtName" runat="server" Width="120" />
            </td>
            <td style="width: 100px;background-color:#003399; color:#CCCCFF;">
              <b> ContentType:</b><br />
                <asp:TextBox ID="txtContentType" runat="server" Width="120" />
            </td>
            <td style="width: 100px;background-color:#003399; color:#CCCCFF;">
               <b>Data:</b><br />
                <asp:TextBox ID="txtData" runat="server" Width="120" />
            </td>
            <td style="background-color:#003399; color:#CCCCFF;" class="style1">
                <asp:Button ID="btnAdd" runat="server" CssClass="btn btn-info" Text="Add" 
                    OnClick="Insert" Width="187px" />
            </td>
        </tr>
    </table>







</asp:Content>