asp.net 에서 gridview 의 조회,페이지 나 누 기,업데이트 편집,삭 제 된 인 스 턴 스 코드

1.A,실행 효과 도

1.B,소스 코드/appData/sql-basic.sql

use master
go
if exists(select * from sysdatabases where name='db1')
begin
    drop database db1
end
go
create database db1
go
use db1
go
-- ================================
-- ylb:1,
-- ================================
create table category
(
    categoryid int identity(1,1) primary key,    -- 【PK】
    categoryname varchar(20) not null            --
)

 

insert into category(categoryname) values(' ')
insert into category(categoryname) values(' ')
insert into category(categoryname) values(' ')
insert into category(categoryname) values(' ')

-- ================================
-- ylb:2,
-- ================================
create table product
(
    productid int identity(1001,1) primary key,    -- 【PK】
    productname varchar(20),        --
    unitprice numeric(7,2),            --
    special varchar(10) check(special in(' ',' ')),    -- 【C】
    categoryid int foreign key references category(categoryid)    -- 【FK】
)

insert into product(productname,unitprice,special,categoryid) values(' 1',12.6,' ',1)
insert into product(productname,unitprice,special,categoryid) values(' 2',12.6,' ',1)
insert into product(productname,unitprice,special,categoryid) values(' 3',12.6,' ',1)
insert into product(productname,unitprice,special,categoryid) values(' 4',12.6,' ',1)
insert into product(productname,unitprice,special,categoryid) values(' 5',12.6,' ',1)
insert into product(productname,unitprice,special,categoryid) values(' 6',12.6,' ',1)
insert into product(productname,unitprice,special,categoryid) values(' 7',12.6,' ',1)
insert into product(productname,unitprice,special,categoryid) values(' 8',12.6,' ',1)
insert into product(productname,unitprice,special,categoryid) values(' 1',12.6,' ',2)
insert into product(productname,unitprice,special,categoryid) values(' 1',12.6,' ',3)
insert into product(productname,unitprice,special,categoryid) values(' 1',12.6,' ',4)

select * from category
select productid,productname,unitprice,special,categoryid from product

,2/App_Code//App_Code/DBConnection.cs

using System.Data.SqlClient;
/// <summary>
///DBConnection
///
/// </summary>
public class DBConnection
{
    SqlConnection con = null;

    public DBConnection()
    {
        //
        con = new SqlConnection("Server=.;Database=db1;Uid=sa;pwd=sa");
    }

    /// <summary>
    ///
    /// </summary>
    public SqlConnection Con
    {
        get { return con; }
        set { con = value; }
    }
}

/App_Code/CategoryInfo.cs/App_Code/CategoryOper.cs/App_Code/ProductInfo.cs

using System;

/// <summary>
///ProductInfo
///
/// </summary>
public class ProductInfo
{
    //1,Attributes
    int productId;
    string productName;
    decimal unitprice;
    string special;
    int categoryId;

    public ProductInfo()
    {
        //
        //TODO:
        //
    }
    //3,

    /// <summary>
    /// 【PK】
    /// </summary>
    public int ProductId
    {
        get { return productId; }
        set { productId = value; }
    }
    /// <summary>
    ///
    /// </summary>
    public string ProductName
    {
        get { return productName; }
        set { productName = value; }
    }
    /// <summary>
    ///
    /// </summary>
    public decimal Unitprice
    {
        get { return unitprice; }
        set { unitprice = value; }
    }
    /// <summary>
    /// 【C】( 、 )
    /// </summary>
    public string Special
    {
        get { return special; }
        set { special = value; }
    }
    /// <summary>
    /// 【FK】
    /// </summary>
    public int CategoryId
    {
        get { return categoryId; }
        set { categoryId = value; }
    }
}

/App_Code/ProductOper.cs

using System;
using System.Collections.Generic;

using System.Data.SqlClient;
/// <summary>
///ProductOper
/// </summary>
public class ProductOper
{
    /// <summary>
    /// 1,GetAll
    /// </summary>
    /// <returns></returns>
    public static IList<ProductInfo> GetAll()
    {
        IList<ProductInfo> dals = new List<ProductInfo>();
        string sql = "select productId,productName,unitprice,special,categoryId from Product order by productId desc";

        //1,
        SqlConnection con = new DBConnection().Con;
        //2,
        SqlCommand cmd = con.CreateCommand();

        //3, sql
        cmd.CommandText = sql;

        //4,
        con.Open();
        try
        {
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    ProductInfo dal = new ProductInfo()
                    {
                        ProductId = sdr.GetInt32(0),
                        ProductName = sdr.GetString(1),
                        Unitprice = sdr.GetDecimal(2),
                        Special = sdr.GetString(3),
                        CategoryId = sdr.GetInt32(4)
                    };

                    dals.Add(dal);
                }
            }
        }
        finally
        {
            //, ( )
            con.Close();
        }
        return dals;
    }

    public static void Add(ProductInfo dal)
    {
        string sql = "insert into Product(productName,unitprice,special,categoryId) values(@productName,@unitprice,@special,@categoryId)";

        SqlConnection con = new DBConnection().Con;
        SqlCommand cmd = con.CreateCommand();

        cmd.CommandText = sql;
        //
        cmd.Parameters.Add(new SqlParameter("@productName",dal.ProductName));
        cmd.Parameters.Add(new SqlParameter("@unitprice",dal.Unitprice));
        cmd.Parameters.Add(new SqlParameter("@special", dal.Special));
        cmd.Parameters.Add(new SqlParameter("@categoryId", dal.CategoryId));

        con.Open();
        try
        {
            cmd.ExecuteNonQuery();
        }
        finally {
            con.Close();
        }

    }
    public static void Update(ProductInfo dal)
    {
        string sql = "update Product set productName=@productName,unitprice=@unitprice,special=@special,categoryId=@categoryId where productId=@productId";

        SqlConnection con = new DBConnection().Con;
        SqlCommand cmd = con.CreateCommand();

        cmd.CommandText = sql;
        //
        cmd.Parameters.Add(new SqlParameter("@productName", dal.ProductName));
        cmd.Parameters.Add(new SqlParameter("@unitprice", dal.Unitprice));
        cmd.Parameters.Add(new SqlParameter("@special", dal.Special));
        cmd.Parameters.Add(new SqlParameter("@categoryId", dal.CategoryId));
        cmd.Parameters.Add(new SqlParameter("@productId", dal.ProductId));
        con.Open();
        try
        {
            cmd.ExecuteNonQuery();
        }
        finally
        {
            con.Close();
        }

    }
    public static void Delete(int productId)
    {
        string sql = "delete Product where productId=@productId";

        SqlConnection con = new DBConnection().Con;
        SqlCommand cmd = con.CreateCommand();

        cmd.CommandText = sql;
        //
        cmd.Parameters.Add(new SqlParameter("@productId", productId));
        con.Open();
        try
        {
            cmd.ExecuteNonQuery();
        }
        finally
        {
            con.Close();
        }

    }
    public ProductOper()
    {
        //
        //TODO:
        //
    }
}

,8/Default.aspx

<%@ 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:HyperLink ID="hlCreate" runat="server" Text=" " NavigateUrl="Create.aspx"></asp:HyperLink>
    <asp:GridView ID="gvwProduct" runat="server" AutoGenerateColumns="False"
            onrowcancelingedit="gvwProduct_RowCancelingEdit"
            onrowdatabound="gvwProduct_RowDataBound" onrowdeleting="gvwProduct_RowDeleting"
            onrowediting="gvwProduct_RowEditing"
            onrowupdating="gvwProduct_RowUpdating" Width="700px" AllowPaging="True"
            onpageindexchanging="gvwProduct_PageIndexChanging" PageSize="5">
        <Columns>
            <asp:TemplateField HeaderText=" ">
                <EditItemTemplate>
                    <asp:Label ID="Label6" runat="server" Text='<%# Bind("productId") %>'></asp:Label>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("productId") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText=" ">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("productName") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("productName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText=" ">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("unitprice") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("unitprice") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText=" ">
                <EditItemTemplate>
                    <asp:RadioButtonList ID="RadioButtonList1" runat="server"
                        RepeatDirection="Horizontal" RepeatLayout="Flow">
                        <asp:ListItem> </asp:ListItem>
                        <asp:ListItem> </asp:ListItem>
                    </asp:RadioButtonList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("special") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText=" ">
                <EditItemTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server">
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("categoryId") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ShowEditButton="True" />
            <asp:CommandField ShowDeleteButton="True" />
        </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

/Default.aspx.cs

using System;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    /// <summary>
    /// 1,
    /// </summary>
    private void Bind()
    {
        gvwProduct.DataSource = ProductOper.GetAll();
        gvwProduct.DataBind();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }
    protected void gvwProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        //
        Label productIdLabel = (Label)gvwProduct.Rows[e.RowIndex].FindControl("Label1");
        int productId = Convert.ToInt32(productIdLabel.Text);

        //
        ProductOper.Delete(productId);

        //
        Bind();
    }
    protected void gvwProduct_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // ,
            e.Row.Cells[6].Attributes.Add("onclick", "return confirm(' !')");
        }
    }
    protected void gvwProduct_RowEditing(object sender, GridViewEditEventArgs e)
    {

        Label specialLabel = (Label)gvwProduct.Rows[e.NewEditIndex].FindControl("Label4");
        Label categoryIdLabel = (Label)gvwProduct.Rows[e.NewEditIndex].FindControl("Label5");

        //
        gvwProduct.EditIndex = e.NewEditIndex;  //( <-) (-> )

        //
        Bind();

        RadioButtonList specialRadioButtonList = (RadioButtonList)gvwProduct.Rows[e.NewEditIndex].FindControl("RadioButtonList1");
        DropDownList categoryIdDropDownList = (DropDownList)gvwProduct.Rows[e.NewEditIndex].FindControl("DropDownList1");
        specialRadioButtonList.SelectedValue = specialLabel.Text;
        categoryIdDropDownList.DataSource = CategoryOper.GetAll();
        categoryIdDropDownList.DataTextField = "categoryName";
        categoryIdDropDownList.DataValueField = "categoryId";
        categoryIdDropDownList.DataBind();
        categoryIdDropDownList.SelectedValue = categoryIdLabel.Text;

      
    }
    protected void gvwProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //
        gvwProduct.EditIndex = -1;

        //
        Bind();
    }
    protected void gvwProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //

        //1,
        Label productIdLabel = (Label)gvwProduct.Rows[e.RowIndex].FindControl("Label6");
        TextBox productNameTextBox = (TextBox)gvwProduct.Rows[e.RowIndex].FindControl("TextBox2");
        TextBox unitpriceTextBox = (TextBox)gvwProduct.Rows[e.RowIndex].FindControl("TextBox3");
        RadioButtonList specialRadioButtonList = (RadioButtonList)gvwProduct.Rows[e.RowIndex].FindControl("RadioButtonList1");
        DropDownList categoryIdDropDownList = (DropDownList)gvwProduct.Rows[e.RowIndex].FindControl("DropDownList1");

        ProductInfo dal = new ProductInfo() {
         ProductId=Convert.ToInt32(productIdLabel.Text),
          ProductName=productNameTextBox.Text,
           Unitprice=Convert.ToDecimal(unitpriceTextBox.Text),
            Special=specialRadioButtonList.SelectedValue,
             CategoryId=Convert.ToInt32(categoryIdDropDownList.SelectedValue)
        };
        //2,
        ProductOper.Update(dal);

        //
        gvwProduct.EditIndex = -1;

        //
        Bind();

    }
    protected void gvwProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvwProduct.PageIndex = e.NewPageIndex;

        //
        Bind();
    }
}

/Create.aspx

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

<!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:HyperLink ID="hlDefault" runat="server" Text=" " NavigateUrl="~/Default.aspx"></asp:HyperLink>
    <fieldset>
    <legend> </legend>
    <table width="500px">
     <tr>
    <td> </td>
    <td>
        <asp:TextBox ID="txtProductName" runat="server"></asp:TextBox>
         </td>
    <td></td>
    </tr>
     <tr>
    <td> </td>
    <td>
        <asp:TextBox ID="txtUnitprice" runat="server"></asp:TextBox>
         </td>
    <td></td>
    </tr>
     <tr>
    <td> </td>
    <td>
        <asp:RadioButtonList ID="rblSpecial" runat="server"
            RepeatDirection="Horizontal" RepeatLayout="Flow">
            <asp:ListItem> </asp:ListItem>
            <asp:ListItem Selected="True"> </asp:ListItem>
        </asp:RadioButtonList>
         </td>
    <td></td>
    </tr>
     <tr>
    <td> </td>
    <td>
        <asp:DropDownList ID="dropCategory" runat="server">
        </asp:DropDownList>
         </td>
    <td></td>
    </tr>
     <tr>
    <td></td>
    <td>
        <asp:Button ID="btnAdd" runat="server" Text=" " onclick="btnAdd_Click" />
         </td>
    <td></td>
    </tr>
    </table>
    </fieldset>
    </div>
    </form>
</body>
</html>

/Create.aspx.cs

using System;

public partial class Create : System.Web.UI.Page
{
    /// <summary>
    /// 1,
    /// </summary>
    private void Bind()
    {
        dropCategory.DataSource = CategoryOper.GetAll();
        dropCategory.DataTextField = "categoryName";
        dropCategory.DataValueField = "categoryId";
        dropCategory.DataBind();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        ProductInfo dal = new ProductInfo() {
         ProductName=txtProductName.Text.Trim(),
          Unitprice=Convert.ToDecimal(txtUnitprice.Text.Trim()),
           Special=rblSpecial.SelectedValue,
            CategoryId=Convert.ToInt32(dropCategory.SelectedValue)
        };

        //
        ProductOper.Add(dal);

        Response.Redirect("~/Default.aspx");
    }
}

저자:ylbtech 출처:http://ylbtech.cnblogs.com/

좋은 웹페이지 즐겨찾기