GridView的各个功能

转载 2012年03月28日 16:49:06

GridView控件修改、删除例子,修改时含有DropDownList控件。
示例运行效果图:


GridViewUp.aspx文件代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewUp.aspx.cs" Inherits="gridview_GridViewUp" %>

<!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>
            <table cellpadding="0" cellspacing="0" border="0" width="80%" style="font-size: 11px">
                <tr>
                    <td align="center">
                        <asp:GridView ID="GridView1" runat="server" Width="100%" CellPadding="4" ForeColor="#333333"
                            AutoGenerateColumns="False" AllowPaging="True" PageSize="12" OnRowCancelingEdit="GridView1_RowCancelingEdit"
                            OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting"
                            DataKeyNames="id,name" OnPageIndexChanging="GridView1_PageIndexChanging" DataMember="card,price" OnRowDataBound="GridView1_RowDataBound" GridLines="None">
                            <Columns>
                                <asp:BoundField HeaderText="身份证号" DataField="card" Visible=false />
                                <asp:BoundField HeaderText="编号" DataField="id" ReadOnly="True" />
                                <asp:BoundField DataField="name" HeaderText="姓名" ReadOnly="True" />
                                <asp:TemplateField HeaderText="身份证号">
                                    <ItemTemplate>
                                        <%# Eval("card") %>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="TBCard" Text='<%# Eval("card") %>' runat="server" Width="140px" />
                                    </EditItemTemplate>
                                    <ItemStyle Width="150px" />
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="学历">
                                    <ItemTemplate>
                                        <%# Eval("description")%>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:HiddenField ID="HDFXueli" runat="server" Value='<%# Eval("xueli") %>' />
                                        <asp:DropDownList ID="DDLXueli" runat="server" Width="90px" />
                                    </EditItemTemplate>
                                    <ItemStyle Width="100px" />
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="价格">
                                    <ItemTemplate>
                                        <%# Eval("price") %>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="TBPrice" Text='<%# Eval("price") %>' runat="server" Width="90px" />
                                    </EditItemTemplate>
                                    <ItemStyle Width="100px" />
                                </asp:TemplateField>
                                <asp:BoundField HeaderText="建立时间" DataField="createdate" ReadOnly="True" />
                                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" HeaderText="操作" />
                            </Columns>
                            <PagerSettings FirstPageText="" LastPageText="" NextPageText="" PreviousPageText="" />
                            <RowStyle Height="20px" BackColor="#F7F6F3" ForeColor="#333333" />
                            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                            <EditRowStyle BackColor="#999999" />
                            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

GridViewUp.aspx.cs文件代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class gridview_GridViewUp : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridViewBind();
        }
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridViewBind();
    }

    private void GridViewBind()
    {
        string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
        string SqlStr = "SELECT a.*,b.description FROM test01 a,xueli b where a.xueli=b.code and a.id<1000 and a.id>200";
        DataSet ds = new DataSet();

        try
        {
            SqlConnection conn = new SqlConnection(connStr);
            if (conn.State.ToString() == "Closed") conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(SqlStr, conn);
            da.Fill(ds, "test01");
            if (conn.State.ToString() == "Open") conn.Close();

            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Response.Write("数据库错误,错误原因:" + ex.Message);
            Response.End();
        }
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (((DropDownList)e.Row.FindControl("DDLXueli")) != null)
        {       
            DropDownList ddlxueli = (DropDownList)e.Row.FindControl("DDLXueli");

            // 生成 DropDownList 的值,绑定数据
            string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
            string SqlStr = "SELECT * from xueli";
            DataSet ds = new DataSet();

            SqlConnection conn = new SqlConnection(connStr);
            if (conn.State.ToString() == "Closed") conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(SqlStr, conn);
            da.Fill(ds, "xueli");
            if (conn.State.ToString() == "Open") conn.Close();

            ddlxueli.DataSource = ds.Tables[0].DefaultView;
            ddlxueli.DataTextField = "description";
            ddlxueli.DataValueField = "code";
            ddlxueli.DataBind();
            //

            // 选中 DropDownList
            ddlxueli.SelectedValue = ((HiddenField)e.Row.FindControl("HDFXueli")).Value;
            //
        }
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        GridViewBind();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        GridViewBind();
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
        string card = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TBCard")).Text;
        string xueli = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("DDLXueli")).SelectedValue;
        string price = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TBPrice")).Text;

        string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
        string SqlStr = "update test01 set card='" + card + "',xueli='" + xueli + "',price='" + price + "' where id=" + id;

        try
        {
            SqlConnection conn = new SqlConnection(connStr);
            if (conn.State.ToString() == "Closed") conn.Open();
            SqlCommand comm = new SqlCommand(SqlStr, conn);
            comm.ExecuteNonQuery();
            comm.Dispose();
            if (conn.State.ToString() == "Open") conn.Close();

            GridView1.EditIndex = -1;
            GridViewBind();
        }
        catch (Exception ex)
        {
            Response.Write("数据库错误,错误原因:" + ex.Message);
            Response.End();
        }
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
        string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
        string SqlStr = "delete from test01 where id=" + id;

        try
        {
            SqlConnection conn = new SqlConnection(connStr);
            if (conn.State.ToString() == "Closed") conn.Open();
            SqlCommand comm = new SqlCommand(SqlStr, conn);
            comm.ExecuteNonQuery();
            comm.Dispose();
            if (conn.State.ToString() == "Open") conn.Close();

            GridView1.EditIndex = -1;
            GridViewBind();
        }
        catch (Exception ex)
        {
            Response.Write("数据库错误,错误原因:" + ex.Message);
            Response.End();
        }
    }
}

sql server2000生成表代码:
CREATE TABLE [dbo].[test01] (
    [id] [decimal](18, 0) IDENTITY (1, 1) NOT NULL ,
    [name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [card] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [xueli] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [price] [decimal](18, 0) NULL ,
    [createdate] [datetime] NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[test01] ADD
    CONSTRAINT [DF_test01_createdate] DEFAULT (getdate()) FOR [createdate],
    CONSTRAINT [PK_test01] PRIMARY KEY CLUSTERED
    (
        [id]
    ) ON [PRIMARY]
GO

CREATE TABLE [dbo].[xueli](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [code] [int] NULL,
    [description] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT [PK_xueli] PRIMARY KEY CLUSTERED
(
    [id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

xueli表中的数据:
id    code    description
1    1    博士
2    2    硕士
3    3    学士

GridView功能详细介绍

快速预览:GridView无代码分页排序GridView选中,编辑,取消,删除GridView正反双向排序GridView和下拉菜单DropDownList结合GridView和CheckBox结合鼠...
  • wzhibin
  • wzhibin
  • 2008年03月28日 10:34
  • 5632

C#gridview操作汇总(未整理)

 C# GridView 操作汇总GridView 操作汇总1、自定义列    Customize Cells and Columns in the Windows Forms DataGridVie...
  • zhouboat
  • zhouboat
  • 2008年11月05日 10:13
  • 5263

带搜索功能的GridView控件

Demo代码下载 最近需要一个gridview能够有不错的搜索功能,最好还是个GridView的扩展控件以后可以直接使用。我试着在CSDN上搜了一下下面这两篇文章都是带Search功能的GridVie...
  • dujingjing1230
  • dujingjing1230
  • 2009年10月28日 17:59
  • 2148

ASP.NET实现GridView删除功能

public partial class _Default : System.Web.UI.Page { SqlDataAdapter sda = null; ...
  • woaifen3344
  • woaifen3344
  • 2012年12月21日 22:37
  • 601

GridView控件自定义分页的实现

前人栽树,后人乘凉,话不多说,代码如下:  实现方式一:.aspx: ...
  • yanghua_kobe
  • yanghua_kobe
  • 2009年10月05日 17:15
  • 3433

GridView表格抬头列值复选筛选

这是一个使用jquery lhgdialog弹窗插件筛选GridView的小例子。 下载链接:http://download.csdn.net/detail/windxxf/9140213  用jqu...
  • windxxf
  • windxxf
  • 2015年09月28日 08:48
  • 1502

Gridview控件高级技巧

一 格式化gridview  和asp.net 1.1一样,gridview可以很方便地定制其样式,比如css,颜色等。要定制gridview的格式,十分简单,只需要鼠标右击gridview,在弹出的...
  • hawkjin
  • hawkjin
  • 2007年06月29日 13:33
  • 669

如何设置gridview一个linkbutton点击改变审核状态

1.先在gridview中放一个commandfield  ,修改 删除的相关信息。 2.设置RowDeleting()事件的相关事件。(注:获取所选行的数据: GridView1.Rows[e.R...
  • a6225301
  • a6225301
  • 2014年03月26日 14:47
  • 1358

GridView自身的分页功能的使用方法

用一下,就是把返回的数据集再按GridView中的页大小再拆分一下显示 如返回200条,GridView每页20条,那页便是有10页,每次点上一页或是下一页时,都会去数据库里取回来200条数据,再拆...
  • ty_soft
  • ty_soft
  • 2012年02月24日 19:47
  • 1026

Android ListView/GridView 搜索过滤功能

Android ListView/GridView 搜索过滤功能:   如下图需要实现的功能:在搜索框输入内容,列表只显示与所输内容相同的选项。 实现: 1.给Edi...
  • qq_16566857
  • qq_16566857
  • 2016年10月27日 11:41
  • 750
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:GridView的各个功能
举报原因:
原因补充:

(最多只允许输入30个字)