Recent Posts

ASP.NET: Thêm mới, cập nhật, xóa dữ liệu trên GridView

-

1. Tạo bảng customers trong cơ sở dữ liệu CustomerManage với các trường và kiểu dữ liệu sau:

2. Cấu hình tập tin web.config:
<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5"/>
      <httpRuntime targetFramework="4.5"/>
    </system.web>
  <connectionStrings>
    <add  name="conn" connectionString="Data Source=hiennm;Initial Catalog=CustomerManage;Integrated Security=True"/>
  </connectionStrings>
</configuration>

3. Tập tin Default.aspx (Thiết kế giao diện)
<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="dvGrid" style="padding:10px; width:550px">
<asp:GridView ID="GridView1" runat="server"  Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69A"
HeaderStyle-BackColor = "blue" AllowPaging ="true"  ShowFooter = "true"
OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer"
onrowupdating="UpdateCustomer"  onrowcancelingedit="CancelEdit"
PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px"  HeaderText = "CustomerID">
    <ItemTemplate>
        <asp:Label ID="lblCustomerID" runat="server"
        Text='<%#Eval("CustomerID")%>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtCustomerID" Width = "40px"
            MaxLength = "5" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Name">
    <ItemTemplate>
        <asp:Label ID="lblContactName" runat="server"
                Text='<%#Eval("ContactName")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtContactName" runat="server"
            Text='<%#Eval("ContactName")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtContactName" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px"  HeaderText = "Company">
    <ItemTemplate>
        <asp:Label ID="lblCompany" runat="server"
            Text='<%#Eval("CompanyName")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtCompany" runat="server"
            Text='<%#Eval("CompanyName")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtCompany" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton ID="lnkRemove" runat="server"
            CommandArgument = '<%#Eval("CustomerID")%>'
         OnClientClick = "return confirm('Do you want to delete?')"
        Text = "Delete" OnClick = "DeleteCustomer"></asp:LinkButton>
    </ItemTemplate>
    <FooterTemplate>
        <asp:Button ID="btnAdd" runat="server" Text="Add"
            OnClick = "AddNewCustomer" />
    </FooterTemplate>
</asp:TemplateField>
<asp:CommandField  ShowEditButton="True" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69A"  />
</asp:GridView>
</div>
</form>
</body>
</html>

4. File Default.aspx.cs (Mã nguồn C#)
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Configuration;

public partial class Insert_Update_Delete: System.Web.UI.Page
{
    private StringstrConnString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    private voidBindData(){
        stringstrQuery = "select CustomerID,ContactName,CompanyName" +
                           " from customers";
        SqlCommandcmd = new SqlCommand(strQuery);
        GridView1.DataSource = GetData(cmd);
        GridView1.DataBind();
    }
    private DataTableGetData(SqlCommand cmd){
        DataTabledt = new DataTable();
        SqlConnectioncon = new SqlConnection(strConnString);
        SqlDataAdaptersda = new SqlDataAdapter();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        returndt;
    }
  
    protected voidPage_Load(object sender, EventArgse){
        if(!IsPostBack)
        {
            BindData();
        }
    }
    protected voidAddNewCustomer(object sender, EventArgse){
        stringCustomerID = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text;
        stringName = ((TextBox)GridView1.FooterRow.FindControl("txtContactName")).Text;
        stringCompany = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
        SqlConnectioncon = new SqlConnection(strConnString);
        SqlCommandcmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into customers(CustomerID, ContactName, CompanyName) "+
        "values(@CustomerID, @ContactName, @CompanyName);" +
        "select CustomerID,ContactName,CompanyName from customers";
        cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID;
        cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name;
        cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company;
        GridView1.DataSource = GetData(cmd);
        GridView1.DataBind();
    }
    protected voidEditCustomer(object sender, GridViewEditEventArgse)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindData();
    }
    protected voidCancelEdit(object sender, GridViewCancelEditEventArgse)
    {
        GridView1.EditIndex = -1;
        BindData();
    }
    protected voidUpdateCustomer(object sender, GridViewUpdateEventArgse)
    {
        stringCustomerID = ((Label)GridView1.Rows[e.RowIndex]
                            .FindControl("lblCustomerID")).Text;
        stringName = ((TextBox)GridView1.Rows[e.RowIndex]
                            .FindControl("txtContactName")).Text;
        stringCompany = ((TextBox)GridView1.Rows[e.RowIndex]
                            .FindControl("txtCompany")).Text;
        SqlConnectioncon = new SqlConnection(strConnString);
        SqlCommandcmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "update customers set ContactName=@ContactName," +
         "CompanyName=@CompanyName where CustomerID=@CustomerID;" +
         "select CustomerID,ContactName,CompanyName from customers";
        cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID;
        cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name;
        cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company;
        GridView1.EditIndex = -1;
        GridView1.DataSource = GetData(cmd);
        GridView1.DataBind();
    }
    protected voidDeleteCustomer(object sender, EventArgse)
    {
        LinkButtonlnkRemove = (LinkButton)sender;
        SqlConnectioncon = new SqlConnection(strConnString);
        SqlCommandcmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "delete from  customers where "+
        "CustomerID=@CustomerID;"+
         "select CustomerID,ContactName,CompanyName from customers";
        cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value
            = lnkRemove.CommandArgument;
        GridView1.DataSource = GetData(cmd);
        GridView1.DataBind();
    }
    protected voidOnPaging(object sender, GridViewPageEventArgse)
    {
        BindData();
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();
    }
}
Tags: Asp.net, asp, mvc, gridview, vs 2013, visual studio, mfc, c#, vb.net

Related Post:

  • Code C#: Nhập vào 2 số a, b. Tìm ước chung lớn nhất (UCLN) của a và b//Viết chương trình Console Application, nhập vào 2 số a và b. Tìm ước chung lớn nhất (UCLN) của 2 số a, b.class Program{        static void Main(){            inta, b;            do{       … Read More
  • Code C#: Ví dụ vòng lặp FOR//Ví dụ 1: Viết chương trình C# sử dụng cấu trúc FOR in ra màn hình kết quả như sau:****************************using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace FOR_LOOP_1{class Program{static void Main(string[] args){     int i,j;     for(i=0;i<=6;i++){           … Read More
  • Code C#: Nhập vào số nguyên N có 3 chữ số. Tính tổng 3 chữ số đó//Viết chương trình Console Application, nhập vào số nguyên n có 3 chữ số. Hãy tính tổng 3 chữ số đó.namespaceBaiThucHanh1{    class Program{        static void Main(){            int n;            Console.Writ… Read More
  • HTML: Một số thẻ HTML cơ bản1. Thẻ <FONT>:- Dùng định dạng font chữ- Định dạng Font chữ cho cả tài liệu thì đặt tag <Font> trong phần <Body>- Định dạng từng phần hoặc từng từ thì đặt tại vị trí muốn định dạngCú pháp:<FONT Face=”fontName1, fontName2, fontName3” size=”value” Color=”rrggbb”>                      &nb… Read More
  • Code C#: Nhập 2 số từ bàn phím. Hoán vị 2 số đó//Viết chương trình Console Application, nhập vào 2 số a và b từ bàn phím. Hãy hoán vị 2 số đó. Ví dụ: a=5, b=7  => a=7, b=5namespaceLapTrinhCoBan{    class Program{        static void Main(){            inta,b,temp;      … Read More
  • Code C#: Ví dụ cấu trúc IF...ELSE//Viết chương trình cho phép nhập 3 số nguyên từ bàn phím. In ra số lớn nhất.using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Max_3_so{class Program{static void Main(string[] args){int a, b, c;Console.Write("Nhap gia tri a:");a = int.Parse(Console.ReadLine());Console.Write("Nhap gia tri b:");b = int.Parse(Console.ReadLine());… Read More




Klik untuk melihat kode: :) =( :s :D :-D ^:D ^o^ 7:( :Q :p T_T @@, :-a :W *fck* x@