欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

asp.net中g(shù)ridview的查詢、分頁、編輯更新、刪除的實例代碼

 更新時間:2013年03月19日 17:09:19   作者:  
asp.net中g(shù)ridview的查詢、分頁、編輯更新、刪除的實例代碼,需要的朋友可以參考一下

1.A,運行效果圖

1.B,源代碼
/App_Data/sql-basic.sql

復(fù)制代碼 代碼如下:

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,產(chǎn)品表
-- ================================
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

復(fù)制代碼 代碼如下:

using System.Data.SqlClient;
/// <summary>
///DBConnection 的摘要說明
///數(shù)據(jù)連接類
/// </summary>
public class DBConnection
{
    SqlConnection con = null;

    public DBConnection()
    {
        //創(chuàng)建連接對象
        con = new SqlConnection("Server=.;Database=db1;Uid=sa;pwd=sa");
    }

    /// <summary>
    /// 數(shù)據(jù)連接對象
    /// </summary>
    public SqlConnection Con
    {
        get { return con; }
        set { con = value; }
    }
}

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

復(fù)制代碼 代碼如下:

using System;

/// <summary>
///ProductInfo 的摘要說明
///產(chǎn)品實體類
/// </summary>
public class ProductInfo
{
    //1,Attributes
    int productId;
    string productName;
    decimal unitprice;
    string special;
    int categoryId;

    public ProductInfo()
    {
        //
        //TODO: 在此處添加構(gòu)造函數(shù)邏輯
        //
    }
    //3,

    /// <summary>
    /// 產(chǎn)品編號【PK】
    /// </summary>
    public int ProductId
    {
        get { return productId; }
        set { productId = value; }
    }
    /// <summary>
    /// 產(chǎn)品名稱
    /// </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

復(fù)制代碼 代碼如下:

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,創(chuàng)建連接對象
        SqlConnection con = new DBConnection().Con;
        //2,創(chuàng)建命令對象
        SqlCommand cmd = con.CreateCommand();

        //3,把sql語句付給命令對象
        cmd.CommandText = sql;

        //4,打開數(shù)據(jù)連接
        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
        {
            //,關(guān)閉數(shù)據(jù)連接(釋放資源)
            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;
        //配參數(shù)
        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;
        //配參數(shù)
        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;
        //配參數(shù)
        cmd.Parameters.Add(new SqlParameter("@productId", productId));
        con.Open();
        try
        {
            cmd.ExecuteNonQuery();
        }
        finally
        {
            con.Close();
        }

    }
    public ProductOper()
    {
        //
        //TODO: 在此處添加構(gòu)造函數(shù)邏輯
        //
    }
}

,8
/Default.aspx

復(fù)制代碼 代碼如下:

<%@ 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="產(chǎn)品編號">
                <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="產(chǎn)品名稱">
                <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

復(fù)制代碼 代碼如下:

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

public partial class _Default : System.Web.UI.Page
{
    /// <summary>
    /// 1,展示產(chǎn)品
    /// </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)
    {
        //刪除一行數(shù)據(jù)
        Label productIdLabel = (Label)gvwProduct.Rows[e.RowIndex].FindControl("Label1");
        int productId = Convert.ToInt32(productIdLabel.Text);

        //調(diào)用刪除方法
        ProductOper.Delete(productId);

        //更新數(shù)據(jù)
        Bind();
    }
    protected void gvwProduct_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //給單元格,添加單擊事件
            e.Row.Cells[6].Attributes.Add("onclick", "return confirm('您確定要刪除該行數(shù)據(jù)!')");
        }
    }
    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;  //(普通模式<-)分水嶺(->編輯模式)

        //更新數(shù)據(jù)
        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;

        //更新數(shù)據(jù)
        Bind();
    }
    protected void gvwProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //更新數(shù)據(jù)

        //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,調(diào)用方法
        ProductOper.Update(dal);

        //取消編輯模式
        gvwProduct.EditIndex = -1;

        //更新數(shù)據(jù)
        Bind();

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

        //更新數(shù)據(jù)
        Bind();
    }
}

/Create.aspx

復(fù)制代碼 代碼如下:

<%@ 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="產(chǎn)品列表" NavigateUrl="~/Default.aspx"></asp:HyperLink>
    <fieldset>
    <legend>添加商品</legend>
    <table width="500px">
     <tr>
    <td>產(chǎn)品名稱</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

復(fù)制代碼 代碼如下:

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)
        };

        //調(diào)用添加方法
        ProductOper.Add(dal);

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


作者:ylbtech
出處:http://ylbtech.cnblogs.com/

相關(guān)文章

  • ASP.Net Core對USB攝像頭進行截圖

    ASP.Net Core對USB攝像頭進行截圖

    這篇文章介紹了ASP.Net Core對USB攝像頭進行截圖的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-10-10
  • ASP.NET?Core?MVC中Tag?Helpers用法介紹

    ASP.NET?Core?MVC中Tag?Helpers用法介紹

    這篇文章介紹了ASP.NET?Core?MVC中Tag?Helpers的用法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-02-02
  • ASP.NET?MVC實現(xiàn)下拉框多選

    ASP.NET?MVC實現(xiàn)下拉框多選

    這篇文章介紹了ASP.NET?MVC實現(xiàn)下拉框多選的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-09-09
  • asp.net中session的原理及應(yīng)用詳解

    asp.net中session的原理及應(yīng)用詳解

    Session是一種Web會話中的常用狀態(tài)之一,Session提供了一種把信息保存在服務(wù)器內(nèi)存中的方式。他能儲存任何數(shù)據(jù)類型,包含自定義對象,本文將詳細介紹asp.net中session的原理及應(yīng)用,需要的朋友可以參考下
    2012-11-11
  • C#操作Excel數(shù)據(jù)增刪改查示例

    C#操作Excel數(shù)據(jù)增刪改查示例

    Excel數(shù)據(jù)增刪改查我們可以使用c#進行操作,首先創(chuàng)建ExcelDB.xlsx文件,并添加兩張工作表,接下按照下面的操作步驟即可
    2013-11-11
  • IIS部署asp.net mvc網(wǎng)站的方法

    IIS部署asp.net mvc網(wǎng)站的方法

    這篇文章主要為大家詳細介紹了IIS部署asp.net mvc網(wǎng)站的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-10-10
  • asp.net(C#)生成無限級別菜單

    asp.net(C#)生成無限級別菜單

    最近開發(fā)的一個項目中用到了無限級別菜單,因此將此代碼貼出來,以供研究,開發(fā)環(huán)境為VS2008+SQL 2000。
    2010-03-03
  • 為HttpClient添加默認請求報頭的四種解決方案

    為HttpClient添加默認請求報頭的四種解決方案

    這篇文章主要給大家介紹了關(guān)于為HttpClient添加默認請求報頭的四種解決方案,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用HttpClient具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • Ajax+asp.net實現(xiàn)用戶登陸

    Ajax+asp.net實現(xiàn)用戶登陸

    這篇文章主要介紹了Ajax+asp.net實現(xiàn)用戶登陸,主要是為了練習(xí)ajax的使用方法,有需要的小伙伴參考下。
    2015-03-03
  • .net非托管資源的回收方法

    .net非托管資源的回收方法

    這篇文章主要介紹了.net非托管資源的回收方法,以實例形式詳細分析歸納了.net非托管資源的兩種回收方法,具有一定的參考借鑒價值,需要的朋友可以參考下
    2014-10-10

最新評論