Asp.net中GridView使用详解(引)

目录

  1. ASP.NET
    MVC搭建项目后台UI框架—① 、后台主框架
  2. ASP.NET
    MVC搭建项目后台UI框架—二 、菜单特效
  3. ASP.NET
    MVC搭建项目后台UI框架—③ 、面板折叠和进展
  4. ASP.NET
    MVC搭建项目后台UI框架—④ 、tab多页签帮忙
  5. ASP.NET
    MVC搭建项目后台UI框架—伍 、Demo演示Controller和View的交互
  6. ASP.NET
    MVC搭建项目后台UI框架—⑥ 、客户保管(添加、修改、查询、分页)
  7. ASP.NET
    MVC搭建项目后台UI框架—柒 、总结报表
  8. ASP.NET
    MVC搭建项目后台UI框架—八 、将View中甄选的数额行中的一部分数据传入到Controller中
  9. ASP.NET
    MVC搭建项目后台UI框架—九 、服务器端排序
  10. ASP.NET
    MVC搭建项目先天UI框架—十 、导出excel(数据量大,11分耗费时间的,异步导出)

这一节,笔者将用一个德姆o来演示在此UI框架中,控制器和视图的相互。以渠道管理为例。效果图如下:

按回车执行查询,不是F5,笔误。

葡京网上娱乐场 1葡京网上娱乐场 2葡京网上娱乐场 3

那里本身利用了依照jquery的模态窗体组件lhgdialog和表格组件dataTables。dataTables越来越多质感请参见:http://dt.thxopen.com/example/

lhgdialog更多材质请参考:http://www.lhgdialog.com/api/

GridView无代码分页排序
GridView选中,编辑,取消,删除
GridView正面与反面双向排序
GridView和下拉菜单DropDownList结合
GridView和CheckBox结合
鼠标移到GridView某一行时改变该行的背景观方法一
鼠标移到GridView某一行时改变该行的背景象方法二
GridView完毕删除时弹出肯定对话框
GridView实现自动编号
GridView达成自定义时间货币等字符串格式
GridView完毕用“…”代替超长字符串
GridView一般换行与强制换行
GridView呈现隐藏某一列
GridView弹出新页面/弹出新窗口
GridView固定表头(不用javascript只用CSS,2行代码,很好用)
GridView合并表头多重表头无错完美版(以联合3列3行比方)
GridView非凡展现某一单元格(例如金额低于多少,分数不及格等)
GridView参与自动求和求平均值小计
GridView
数码导入Excel/Excel数据读入GridView**

Action

① 、在我们的MVC项目中的Models文件夹中,添加一个model类ChannelInfo.cs,因为项目中的O奥迪Q5M框架使用的是Nhibernate,所以属性前面加了virtual

   public class ChannelInfo
    {
       public virtual int ID { get; set; }

       public virtual string ChannelStyle { get; set; }

       public virtual string ChannelCode { get; set; }
       public virtual string CnName { get; set; }
       public virtual string EnName { get; set; }

       public virtual string Status { get; set; }
    }

② 、添加控制器ChannelController,那里为了演示,笔者动用的假数据

葡京网上娱乐场 4葡京网上娱乐场 5

public class ChannelController : Controller
    {
        //
        // GET: /Channel/

        public ActionResult Index()
        {
            return View();
        }
        //添加渠道
        public ActionResult AddChannel()
        {
            return View();
        }

        [HttpPost]
        public JsonResult List(ChannelInfo filter)
        {
            List<ChannelInfo> list = new List<ChannelInfo>();
            for (int i = 0; i < 1100; i++)
            {
                list.Add(new ChannelInfo
            {
                ID = 1,
                ChannelCode = "E_Express"+i,
                ChannelStyle = "香港E特快"+i,
                CnName = "香港E特快"+i,
                EnName = "HK E-Express"+i,
                Status = "1"
            });
            }
            if (!string.IsNullOrEmpty(filter.ChannelCode))
            {
                list = list.Where(x => x.ChannelCode == filter.ChannelCode.Trim()).ToList();
            }
            if (!string.IsNullOrEmpty(filter.CnName))
            {
                list = list.Where(x => x.CnName == filter.CnName.Trim()).ToList();
            }
            if (!string.IsNullOrEmpty(filter.EnName))
            {
                list = list.Where(x => x.EnName == filter.EnName.Trim()).ToList();
            }

            //构造成Json的格式传递 iTotalRecords :总记录数 iTotalDisplayRecords :每页显示的记录数
            var result = new { iTotalRecords = 1100, iTotalDisplayRecords = 10, data = list };
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }

View Code

3、修改_Layout.cshtml,因为背后的View会用到

葡京网上娱乐场 6葡京网上娱乐场 7

<!DOCTYPE html>
<html lang="zh">
    <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <meta charset="utf-8" />
        <title>财务管理 @ViewBag.Title</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
@*      @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")*@
        <link href="~/Content/sharestyle.css" rel="stylesheet" />
        <link href="~/Content/main.css" rel="stylesheet" />
        <script src="~/Scripts/jquery-1.8.3.min.js"></script>
        <script src="~/Lib/lhgdialog/lhgdialog.min.js?self=true&skin=iblue"></script>
    </head>
    <body>
          @*  @RenderSection("featured", required: false)*@
            <section class="content-wrapper main-content clear-fix">
                @RenderBody()
            </section>
        @*<footer>
            <div class="copyright"> ©2015 </div>
           <div class="content-wrapper">
                <div class="float-left">
                    <p>&copy; @DateTime.Now.Year - 我的 ASP.NET MVC 应用程序</p>
                </div>
            </div>
        </footer>*@
@*        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)*@
    </body>
</html>

View Code

四 、添加水道管理的视图Index,代码非常粗略,小编都添加了详细的注释,相信大家都看得懂。那里根本只添加了列表展现,和查询过滤,分页排序。datables是匡助服务器端分页排序的,不过自个儿那边只写了客户端排序,就是先1次性把持有的数据查出来,然后再开始展览分页排序。在数据量小的状态下,体验仍然相当正确的,也简要。假如数据量大,就要启用服务器分页,即每一遍按需取数据,关于datables服务器分页网上.NET的事例相当少,不过经过查找,笔者早就完成了,只是此体系没有写出来。同时datables是永葆缓存的,具体使用大家能够参见小编上边发的网址,笔者那边只做个大致的引进。
那里不佳意思忘了测试包容性难点,后边提供的源代码中Index视图那里包容性有题目,对话框样式争辩了,在源码中请将

tbody{ height:50px;}   修改为 #table_local tbody{ height:50px;}

葡京网上娱乐场 8葡京网上娱乐场 9

@{
    ViewBag.Title = "Index";

}
<style type="text/css">
    html, body
    {
        overflow:hidden;
    }
    #table_local tbody
    {
         height:50px;
    }
    table
    {
          overflow-y:auto;
          overflow-x:hidden;
    }
</style>
<link href="~/Lib/DataTables-1.10.6/media/css/jquery.dataTablesNew.css" rel="stylesheet" />
<script src="~/Lib/DataTables-1.10.6/media/js/jquery.dataTables.min.js"></script>
<script src="~/Content/DataTablesExt.js"></script>
<script type="text/javascript">
    //查询 刷新
    function reloadList() {
        var tables = $('#table_local').dataTable().api();//获取DataTables的Api,详见 http://www.datatables.net/reference/api/
        tables.ajax.reload();
    }
    function deleteRecord(id) {
        $.dialog.confirm("确定要删除吗?", function () { $.dialog.alert("删除成功!"); }, null)
    }
    function successFun() {
        $.dialog.alert("渠道添加成功!");
    }
    //弹出框  
    var dg;
    function showPublishWin() {
        dg = new $.dialog({
            id: "AddChannel",
            title: "添加渠道",
            content: "url:/Channel/AddChannel",
            width: 424,
            height: 320,
            max: false,
            min: false,
            lock: true,
            close: true,
            cancel: true, //X按钮是否显示,如果设置了回调函数,一定会显示  
            //cancel: controlAllBtn,  
            ok: successFun //点击确定执行的回调函数
        });
        dg.show();
    }
    document.onkeydown = function (event) {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if (e && e.keyCode == 27) { // 按 Esc 
            //要做的事情
        }
        if (e && e.keyCode == 13) { // enter 键
            //要做的事情
            reloadList();
        }
    };
</script>
<script type="text/javascript">
    $(function () {
        var h = $(document).height() - 258;
        $("#table_local").dataTable({
            //"iDisplayLength": 10,//每页显示10条数据
            //这里也可以设置分页,但是不能设置具体内容,只能是一维或二维数组的方式,所以推荐下面language里面的写法。
            //"aLengthMenu": [[10, 15, 20, 25, 50, -1], [10, 15, 20, 25, 50, "All"]],
            bProcessing: true,
            //"dom": 'i,p',//l - Length changing  选择每页显示行数下拉框的控件 f - Filtering input  搜索过滤控件t - The Tabletools    导出excel,csv的按钮
            //i - Information  显示汇总信息(从 1 到 100 /共 1,288 条数据) p - Pagination   分页控件 r - pRocessing   显示加载时的进度条 C - copy 显示复制,excel的控件
            //ajax: "/SendGoods/List",
            "scrollY": h,  //垂直滚动
            "scrollCollapse": "true", //开启滚动
            "dom": 'tr<"bottom"lip><"clear">', //这个是控制布局的,不是很好理解
            "bServerSide": false,                    //指定从服务器端获取数据  
            sServerMethod: "POST", //请求方式
            sAjaxSource: "@Url.Action("List", "Channel")", //数据源
            "fnServerParams": function (aoData) {  //查询条件
                aoData.push(
                    { "name": "ChannelCode", "value": $("#ChannelCode").val() },
                    { "name": "CnName", "value": $("#CnName").val() },
                    { "name": "EnName", "value": $("#EnName").val() }
                    );
            },
            columns: [
               {
                   title: "1",
                   "visible": false,
                   "data": "ID", "sClass": "center",    //样式
                   orderable: false,    //该列不排序
                   "render": function (data, type, row) {    //列渲染
                       return "<label class='position-relative'><input id='cbx" + data + "' type='checkbox' onclick='controlSelectAll(" + data + ")' class='cbx' value='" + data + "'/>";
                   }
               },
               { "data": "ChannelCode", title: "渠道代码" },
               { "data": "ChannelStyle", title: "渠道类别" },
               { "data": "CnName", title: "中文名" },
               { "data": "EnName", title: "英文名" },
               {
                   "data": "Status", title: "是否启用", orderable: false, "render": function (data, type, row, meta) { //自定义列
                       if (data == "1") {
                           return "是";
                       }
                       else {
                           return "否";
                       }
                   }
               }
               , {
                   "data": "ID", orderable: false, title: "操作", "render": function (data, type, row, meta) { //自定义列
                       return "<a style='visibility:visible' onclick='deleteRecord(" + data + ")'>删除</a>";
                   }
               }
            ],
            paging: true,//分页
            ordering: true,//是否启用排序
            searching: false,//搜索
            language: {
                lengthMenu: '每页显示:<select class="form-control input-xsmall">' + '<option value="5">5</option>' + '<option value="10">10</option>' + '<option value="15">15</option>'
                    + '<option value="20">20</option>' + '<option value="25">25</option>' + '<option value="30">30</option>' + '<option value="35">35</option>' + '<option value="40">40</option>',//左上角的分页大小显示。
                search: '搜索:',//右上角的搜索文本,可以写html标签

                paginate: {//分页的样式内容。
                    previous: "上一页",
                    next: "下一页",
                    first: "",
                    last: ""
                },

                zeroRecords: "暂无记录",//table tbody内容为空时,tbody的内容。
                //下面三者构成了总体的左下角的内容。
                info: "总共 (_PAGES_) 页,显示 _START_ -- _END_ ,共 (_TOTAL_) 条",//左下角的信息显示,大写的词为关键字。初始_MAX_ 条 
                infoEmpty: "0条记录",//筛选为空时左下角的显示。
                infoFiltered: ""//筛选之后的左下角筛选提示,
            },
            pagingType: "full_numbers"//分页样式的类型

        });
       // $("#table_local_filter input[type=search]").css({ width: "auto" });//右上角的默认搜索文本框,不写这个就超出去了。
    });
</script>
    <div class="areabx clear" style="margin-bottom:0px;padding-bottom:0px;">
        @using (Html.BeginForm("List", null, FormMethod.Get, new { @clase = "form-inline", @role = "form" }))
        {
            <div class="areabx_header">渠道管理</div>
            <ul class="formod mgt10">
                <li>渠道代码:@Html.TextBox("ChannelCode","", new {@class="trade-time wid153" })</li>
                <li>渠道中文名:@Html.TextBox("CnName", "",new {@class="trade-time" })</li>
                <li>渠道英文名:@Html.TextBox("EnName", "",new {@class="trade-time" })</li>
            </ul>
            <div class="botbtbx pdb0">
                <input type="button" value="添加渠道" class="btn btn-primary" onclick="showPublishWin()"/>
                <input type="button" value="查询" onclick="reloadList();" class="btn btn-primary">
            </div>
        }
        <div class="tob_box mgt15">
            <table id="table_local" class="display"  cellspacing="0" cellpadding="0" border="0" style="width:100%">
            </table>
        </div>
    </div>

View Code

⑤ 、添加视图AddChannel,那里没写完。本来还打算把修改也丰盛进去的,有趣味的对象能够团结去完结

@{
    ViewBag.Title = "添加渠道";
}
<style type="text/css">
    body {
        overflow:hidden;
    }
</style>
<h2>添加渠道</h2>
<div>开发中...</div>

鉴于要维持和图案给的体裁风格一直,小编修改了dataTables的体制源码

6、按F5运行

框架中用到的js和css、Img:CssJsImg源码

不可胜计本来没写完,不打算写了,作者就先把这几个半成品的源码贴出来吧,免得我又说笔者并未丰裕的知识分享了,尽管是半成品,可是基本的范围都有了。

插曲:本篇小说在此之前都没办法在天涯论坛首页显示的,笔者给的过来是:没有丰裕的知识分享。笔者心拔凉拔凉的。固然字码得不多,然则代码中倾注了自笔者的思想和经验、时间和脑力。精简、通俗、易懂平昔是自家追求的。

支出条件:VS二〇一一

有意中人评论说源码里少了dll,那多个dll都以没用到的,作者以后已经将没用的dll引用删除,所以源码下载地址更新了,给我们带来的辛勤请见谅!

半成品UI框架源码下载:http://pan.baidu.com/s/1c055sw4

只要源码对我们很有帮衬,希望大家给个推荐,当是辅助下小编白白的技巧分享,假若有更好的提出或不一致的看法,能够建议来,我们共同探索。感激!

**

1.GridView无代码分页排序

效果图:
葡京网上娱乐场 10
1.AllowSorting设为True,aspx代码中是AllowSorting=”True”;
2.暗中认可1页10条,假使要修改每页条数,修改PageSize即可,在aspx代码中是PageSize=”12″。
3.暗许的是单向排序的,右击GridView弹出“属性”,选用AllowSorting为True即可。

2.GridView选中,编辑,取消,删除:

效果图:
葡京网上娱乐场 11

后台代码: 您能够选择sqlhelper,本文没用。代码如下:
using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page 
{

//清清月儿http://blog.csdn.net/21aspnet 
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=数据库名;Uid=帐号;Pwd=密码”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }

//删除
    protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
    {
        string sqlstr = “delete from 表 where id='” +
GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
        sqlcon = new SqlConnection(strCon);
        sqlcom = new SqlCommand(sqlstr,sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }

//更新
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 表 set 字段1='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  • “‘,字段2='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim()
  • “‘,字段3='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where id='” 
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }

//取消
    protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        bind();
    }

//绑定
    public void bind()
    {
        string sqlstr = “select * from 表”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “表”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “id” };//主键
        GridView1.DataBind();
        sqlcon.Close();
    }
}

前台根本代码:                             … …
<asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”4″
                        ForeColor=”#333333″ GridLines=”None”
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit”>
                        <FooterStyle BackColor=”#990000″
Font-Bold=”True” ForeColor=”White” />
                        <Columns>
                            <asp:Bound菲尔德 DataField=”身份证号码”
HeaderText=”用户ID” ReadOnly=”True” />
                            <asp:BoundField Data菲尔德=”姓名”
HeaderText=”用户姓名” />
                            <asp:BoundField DataField=”职员和工人性别”
HeaderText=”性别” />
                            <asp:BoundField Data菲尔德=”家庭住址”
HeaderText=”家庭住址” />
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

3.GridView正面与反面双向排序: 意义图:点姓名各三次的排序,点别的也如出一辙能够。
葡京网上娱乐场 12葡京网上娱乐场 13
后台代码:
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 Default3 : System.Web.UI.Page
{

//清清月儿的博客http://blog.csdn.net/21aspnet 
    SqlConnection sqlcon;
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState[“SortOrder”] = “身份证号码”;
            ViewState[“OrderDire”] = “ASC”;
            bind();
        }
    }
    protected void GridView1_Sorting(object sender,
GridViewSortEventArgs e)
    {
        string sPage = e.SortExpression;
        if (ViewState[“SortOrder”].ToString() == sPage)
        {
            if (ViewState[“OrderDire”].ToString() == “Desc”)
                ViewState[“OrderDire”] = “ASC”;
            else
                ViewState[“OrderDire”] = “Desc”;
        }
        else
        {
            ViewState[“SortOrder”] = e.SortExpression;
        }
        bind();
    }

    public void bind()
    {
        
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “飞狐工作室”);
        DataView view = myds.Tables[“飞狐工作室”].DefaultView;
        string sort = (string)ViewState[“SortOrder”] + ” ” +
(string)ViewState[“OrderDire”];
        view.Sort = sort;
        GridView1.DataSource = view;
        GridView1.DataBind();
        sqlcon.Close();
    }
}

前台根本代码: <asp:GridView ID=”GridView1″ runat=”server” AllowSorting=”True”
AutoGenerateColumns=”False”
                        CellPadding=”3″ Font-Size=”9pt”
OnSorting=”GridView1_Sorting” BackColor=”White” BorderColor=”#CCCCCC”
BorderStyle=”None” BorderWidth=”1px”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                             <asp:BoundField Data菲尔德=”身份证编号”
HeaderText=”用户ID” SortExpression=”身份证号码” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” SortExpression=”姓名”/>
                            <asp:BoundField DataField=”职员和工人性别”
HeaderText=”性别” SortExpression=”员工性别”/>
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址”/>
                                
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

 

4.GridView和下拉菜单DropDownList结合:

效果图:
葡京网上娱乐场 14

后台代码: 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 Default4 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList ddl;
        if (!IsPostBack)
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataBind();
            for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
            {
                DataRowView mydrv =
myds.Tables[“飞狐工作室”].DefaultView[i];
                if (Convert.ToString(mydrv[“职员和工人性别”]).Trim() ==
“True”)
                {
                    ddl =
(DropDownList)GridView1.Rows[i].FindControl(“DropDownList1”);
                    ddl.SelectedIndex = 0;
                }
                if (Convert.ToString(mydrv[“职员和工人性别”]).Trim() ==
“False”)
                {
                    ddl =
(DropDownList)GridView1.Rows[i].FindControl(“DropDownList1”);
                    ddl.SelectedIndex = 1;
                }
            }
            sqlcon.Close();
        }
    }
    public SqlDataReader ddlbind()
    {
        string sqlstr = “select distinct 职员和工人性别 from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);
        sqlcon.Open();
        return sqlcom.ExecuteReader();
    }

前台根本代码:
<asp:GridView ID=”GridView1″ runat=”server” AllowSorting=”True”
AutoGenerateColumns=”False”
                        CellPadding=”3″ Font-Size=”9pt” 
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                             <asp:BoundField DataField=”身份证号码”
HeaderText=”用户ID” SortExpression=”身份证编号” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” SortExpression=”姓名”/>
                            <asp:TemplateFieldHeaderText=”职员和工人性别”>
                                <ItemTemplate>
                                    <asp:DropDownList
ID=”DropDownList1″ runat=”server” DataSource='<%# ddlbind()%>’
DataValueField=”职员和工人性别” DataTextField=”职员和工人性别”>
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址”/>
                                
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

 

5.GridView和CheckBox结合:

效果图:
葡京网上娱乐场 15

后台代码:

using System;
using System.Data;
using System.Configuration;
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 Default5 : System.Web.UI.Page
{
//清清月儿http://blog.csdn.net/21aspnet 
    SqlConnection sqlcon;
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }
    protected void CheckBox2_CheckedChanged(object sender, EventArgs
e)
    {
        for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            CheckBox cbox =
(CheckBox)GridView1.Rows[i].FindControl(“CheckBox1”);
            if (CheckBox2.Checked == true)
            {
                cbox.Checked = true;
            }
            else
            {
                cbox.Checked = false;
            }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        SqlCommand sqlcom;
        for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            CheckBox cbox =
(CheckBox)GridView1.Rows[i].FindControl(“CheckBox1”);
            if (cbox.Checked == true)
            {

                string sqlstr = “delete from 飞狐工作室 where
身份证编号='” + GridView1.DataKeys[i].Value + “‘”;
                sqlcom = new SqlCommand(sqlstr, sqlcon);
                sqlcon.Open();
                sqlcom.ExecuteNonQuery();
                sqlcon.Close();
            }
        }
        bind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        CheckBox2.Checked = false;
        for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            CheckBox cbox =
(CheckBox)GridView1.Rows[i].FindControl(“CheckBox1”);
            cbox.Checked = false;
        }
    }
    public void bind()
    {
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “tb_Member”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “身份证编号” };
        GridView1.DataBind();
        sqlcon.Close();
    }
}

前台根本代码:

<asp:GridView ID=”GridView1″ runat=”server” AllowSorting=”True”
AutoGenerateColumns=”False”
                        CellPadding=”3″ Font-Size=”9pt” 
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                             <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:CheckBox ID=”CheckBox1″
runat=”server” />
                                </ItemTemplate>
                            </asp:TemplateField>
                             <asp:BoundField DataField=”身份证编号”
HeaderText=”用户ID” SortExpression=”身份证号码” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” SortExpression=”姓名”/>
                            
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址”/>
                                
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
                     <asp:CheckBox ID=”CheckBox2″ runat=”server”
AutoPostBack=”True” Font-Size=”9pt”
OnCheckedChanged=”CheckBox2_CheckedChanged”
                        Text=”全选” />
                    <asp:Button ID=”Button1″ runat=”server”
Font-Size=”9pt” Text=”取消” OnClick=”Button1_Click” />
                    <asp:Button ID=”Button2″ runat=”server”
Font-Size=”9pt” Text=”删除” OnClick=”Button2_Click” />

 

6.鼠标移到GridView某一行时改变该行的背景观方法一:

效果图:
葡京网上娱乐场 16
做法:
双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        int i;
        //执行循环,保险每条数据都足以创新
        for (i = 0; i < GridView1.Rows.Count; i++)
        {
            //首先判断是不是是数据行
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //当鼠标停留时更改背景观
                e.Row.Attributes.Add(“onmouseover”,
“c=this.style.backgroundColor;this.style.backgroundColor=’#00A9FF'”);
                //当鼠标移开时还原背景象
                e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=c”);
            }
        }

    }

前台代码: <html xmlns=”http://www.w3.org/1999/xhtml
>
<head runat=”server”>
    <title>完毕鼠标划过改变GridView的行背景观 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” DataKeyNames=”身份证号码”
            DataSourceID=”SqlDataSource1″ AllowSorting=”True”
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px” CellPadding=”3″ Font-Size=”12px”
OnRowDataBound=”GridView1_RowDataBound”>
            <Columns>
                <asp:BoundField DataField=”身份证编号”
HeaderText=”身份证编号” ReadOnly=”True” SortExpression=”身份证号码”
/>
                <asp:BoundField DataField=”姓名” HeaderText=”姓名”
SortExpression=”姓名” />
                <asp:Bound菲尔德 DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址” />
                <asp:BoundField DataField=”邮编”
HeaderText=”邮编” SortExpression=”邮政编码” />
            </Columns>
            <FooterStyle BackColor=”White” ForeColor=”#000066″
/>
            <RowStyle ForeColor=”#000066″ />
            <SelectedRowStyle BackColor=”#669999″ Font-Bold=”True”
ForeColor=”White” />
            <PagerStyle BackColor=”White” ForeColor=”#000066″
HorizontalAlign=”Left” />
            <HeaderStyle BackColor=”#006699″ Font-Bold=”True”
ForeColor=”White” />
        </asp:GridView>
        <asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
ConnectionString=”<%$ ConnectionStrings:北风贸易ConnectionString1
%>”
            SelectCommand=”SELECT top 5 [身份证编号], [姓名],
[职工性别], [家庭住址], [邮政编码] FROM [飞狐工作室]”
DataSourceMode=”DataReader”></asp:SqlDataSource>
    
    </div>
    </form>
</body>
</html>

7.鼠标移到GridView某一行时改变该行的背景象方法二:

效果图:
葡京网上娱乐场 17

做法:和下边包车型地铁同样正是代码分化 protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        //int i;
        ////执行循环,保障每条数据都足以立异
        //for (i = 0; i < GridView1.Rows.Count; i++)
        //{
        //    //首先判断是还是不是是数据行
        //    if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        //当鼠标停留时更改背景观
        //        e.Row.Attributes.Add(“onmouseover”,
“c=this.style.backgroundColor;this.style.backgroundColor=’#00A9FF'”);
        //        //当鼠标移开时还原背景象
        //        e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=c”);
        //    }
        //}
        //若是是绑定数据行 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //鼠标经过时,行背景象变 
            e.Row.Attributes.Add(“onmouseover”,
“this.style.backgroundColor=’#E6F5FA'”);
            //鼠标移出时,行背景观变 
            e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=’#FFFFFF'”);
        }

    }

8.GridView完毕删除时弹出肯定对话框:

效果图:
葡京网上娱乐场 18

福寿无疆情势: 双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最终代码如下所示:

    protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        //假使是绑定数据行 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
             if (e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate)
            {
               
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add(“onclick”,
“javascript:return confirm(‘你确认要去除:\”” + e.Row.Cells[1].Text +
“\”吗?’)”);
            }
        }

    }

9.GridView达成机关编号:

效果图:
葡京网上娱乐场 19

达成形式: 双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最终代码如下所示:
    protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        //如若是绑定数据行 //清清月儿http://blog.csdn.net/21aspnet 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ////鼠标经过时,行背景观变 
            //e.Row.Attributes.Add(“onmouseover”,
“this.style.backgroundColor=’#E6F5FA'”);
            ////鼠标移出时,行背景象变 
            //e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=’#FFFFFF'”);

            ////当有编辑列时,防止失误,要加的RowState判断 
            //if (e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate)
            //{
            //   
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add(“onclick”,
“javascript:return confirm(‘你承认要删减:\”” + e.Row.Cells[1].Text +
“\”吗?’)”);
            //}

        }
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[0].Text = id.ToString();
        }

    }

 

瞩目那时最棒把前台的首先列的表头该为“编号”,因为原先的第②列被“吃掉”了。
<asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px” OnRowDataBound=”GridView1_RowDataBound”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证号码”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” />
                            <asp:BoundField DataField=”职员和工人性别”
HeaderText=”性别” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” />
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

10.GridView达成自定义时间货币等字符串格式:

效果图:
图1-未格式化前
葡京网上娱乐场 20
图2-格式化后
葡京网上娱乐场 21
涸泽而渔办法:

在asp.net
2.0中,假使要在绑定列中呈现比如日期格式等,假如用下边包车型大巴章程是体现不断的

<asp :BoundField DataField=”CreationDate” 
DataFormatString=”{0:M-dd-yyyy}” 
HeaderText=”CreationDate” />

首即便出于htmlencode属性私下认可设置为true,已制止XSS攻击,安全起见而用的,所以,能够有以下三种艺术化解

1、

<asp :GridView ID=”GridView1″ runat=”server”>
<columns>
<asp :BoundField DataField=”CreationDate” 
DataFormatString=”{0:M-dd-yyyy}” 
HtmlEncode=”false”
HeaderText=”CreationDate” />
</columns>
</asp>

将htmlencode设置为false即可

别的的化解办法为,使用模版列

<asp :GridView ID=”GridView3″ runat=”server” >
<columns>
<asp :TemplateField HeaderText=”CreationDate” >
<edititemtemplate>
<asp :Label ID=”Label1″ runat=”server” 
Text='<%# Eval(“CreationDate”, “{0:M-dd-yyyy}”) %>’>
</asp>
</edititemtemplate>
<itemtemplate>
<asp :Label ID=”Label1″ runat=”server” 
Text=’<%# Bind(“CreationDate”, “{0:M-dd-yyyy}”) %>’>
</asp>
</itemtemplate>
</asp>
</columns>
</asp>

前台代码: <asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” DataKeyNames=”身份证号码”
            DataSourceID=”SqlDataSource1″ AllowSorting=”True”
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px” CellPadding=”3″ Font-Size=”12px”
OnRowDataBound=”GridView1_RowDataBound”>
            <Columns>
                <asp:BoundField DataField=”身份证编号”
HeaderText=”身份证编号” ReadOnly=”True” SortExpression=”身份证号码”
/>
                <asp:BoundField DataField=”姓名” HeaderText=”姓名”
SortExpression=”姓名” />
                <asp:BoundField DataField=”邮政编码”
HeaderText=”邮政编码” SortExpression=”邮编” />
                <asp:BoundField DataField=”出生日期”
HeaderText=”出生日期” SortExpression=”出生日期” />
                <asp:BoundField DataField=”起薪” HeaderText=”起薪”
SortExpression=”起薪” />
            </Columns>
            <FooterStyle BackColor=”White” ForeColor=”#000066″
/>
            <RowStyle ForeColor=”#000066″ />
            <SelectedRowStyle BackColor=”#669999″ Font-Bold=”True”
ForeColor=”White” />
            <PagerStyle BackColor=”White” ForeColor=”#000066″
HorizontalAlign=”Left” />
            <HeaderStyle BackColor=”#006699″ Font-Bold=”True”
ForeColor=”White” />
        </asp:GridView>
        <asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
ConnectionString=”<%$ ConnectionStrings:西风贸易ConnectionString1
%>”
            SelectCommand=”SELECT top 5 [出生日期], [起薪],
[身份证编号], [姓名], [家园住址], [邮政编码] FROM
[飞狐工作室]”
DataSourceMode=”DataReader”></asp:SqlDataSource>

附录-常用格式化公式: 葡京网上娱乐场,{0:C}  货币;
{0:D4}由0填充的6个字符宽的字段中体现整数;
{0:000.0}四舍五入小数点保留第三人有效数字;
{0:N2}小数点保留3位有效数字;{0:N2}%   小数点保留4位有效数字加百分号;
{0:D}长日期;{0:d}短日期;{0:yy-MM-dd}   例如07-3-25;;{0:yyyy-MM-dd} 
例如2007-3-25

 11.GridView实现用“…”代替超长字符串:

效果图:
葡京网上娱乐场 22
解决方法:数据绑定后过滤每一行即可
for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            DataRowView mydrv;
            string gIntro;
            if (GridView1.PageIndex == 0)
            {
                mydrv =
myds.Tables[“飞狐工作室”].DefaultView[i];//表名
                gIntro =
Convert.ToString(mydrv[“家庭住址”]);//所要处理的字段
                GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
2);
            }
            else
            {
                mydrv = myds.Tables[“飞狐工作室”].DefaultView[i + (5
* GridView1.PageIndex)];
                gIntro = Convert.ToString(mydrv[“家庭住址”]);
                GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
2);
            }
        } 

调用的方法:

    public string SubStr(string sString, int nLeng)
    {
        if (sString.Length <= nLeng)
        {
            return sString;
        }
        string sNewStr = sString.Substring(0, nLeng);
        sNewStr = sNewStr + “…”;
        return sNewStr;
    }

后台全部代码: using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page 
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=西风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState[“SortOrder”] = “身份证号码”;
            ViewState[“OrderDire”] = “ASC”;
            bind();
        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
    {
        string sqlstr = “delete from 飞狐工作室 where 身份证号码='” +
GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
        sqlcon = new SqlConnection(strCon);
        sqlcom = new SqlCommand(sqlstr,sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证号码='” 
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证编号” };
            GridView1.DataBind();
            for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
            {
                DataRowView mydrv;
                string gIntro;
                if (GridView1.PageIndex == 0)
                {
                    mydrv = myds.Tables[“飞狐工作室”].DefaultView[i];
                    gIntro = Convert.ToString(mydrv[“家庭住址”]);
                    GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
    2);
                }
                else
                {
                    mydrv = myds.Tables[“飞狐工作室”].DefaultView[i + (5
    * GridView1.PageIndex)];
                    gIntro = Convert.ToString(mydrv[“家庭住址”]);
                    GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
    2);
                }
            }
            
            sqlcon.Close();
        }
        public string SubStr(string sString, int nLeng)
        {
            if (sString.Length <= nLeng)
            {
                return sString;
            }
            string sNewStr = sString.Substring(0, nLeng);
            sNewStr = sNewStr + “…”;
            return sNewStr;
        }
        protected void GridView1_RowDataBound(object sender,
    GridViewRowEventArgs e)
        {
            //假诺是绑定数据行 
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ////鼠标经过时,行背景象变 
                //e.Row.Attributes.Add(“onmouseover”,
    “this.style.backgroundColor=’#E6F5FA'”);
                ////鼠标移出时,行背景观变 
                //e.Row.Attributes.Add(“onmouseout”,
    “this.style.backgroundColor=’#FFFFFF'”);

            ////当有编辑列时,防止失误,要加的RowState判断 
            //if (e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate)
            //{
            //   
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add(“onclick”,
“javascript:return confirm(‘你承认要去除:\”” + e.Row.Cells[1].Text +
“\”吗?’)”);
            //}

        }
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[0].Text = id.ToString();
        }

    }
}

 11.GridView一般换行与强制换行:

效果图:
葡京网上娱乐场 23
率先设置<asp:BoundField DataField=”家庭住址” HeaderText=”家庭住址” 
ItemStyle-Width=”100″ />
gridview里有一列绑定的数目相当长,显示的时候在一行里面呈现,页面拉得很宽。
原因是再而三英文段为3个完完全全导致的,在RowDataBound中添加上了一句e.Row.Cells[2].Style.Add(“word-break”,
“break-all”)就可以。

设若要给拥有的列扩展此属性:
 protected void Page_Load(object sender, EventArgs e)
    {
        //平时换行
        GridView1.Attributes.Add(“style”,
“word-break:keep-all;word-wrap:normal”);
        //下边那行是电动换行
        GridView1.Attributes.Add(“style”,
“word-break:break-all;word-wrap:break-word”);
        if (!IsPostBack)
        {
             bind();//调用数据绑定即可
        }
    }
总之:善用CSS的word-break:break-all;word-wrap:break-word属性即可,那脾个性是通用的对于执迷不悟的南换行难题都能够化解,不局限于GridView。

 12.GridView展现隐藏某一列: 本方案为月儿独创,区别于网上别的办法,作者以为用3个CheckBox更人性化,这样能够隐藏不须要的列,让用户本身挑选必要出现的列,在处理多列时那是3个很好的解决方案!

效果图:
图1-开始
葡京网上娱乐场 24
图2-点击展现的Check博克斯后
葡京网上娱乐场 25

缓解方案: public void bind()
    {
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “飞狐工作室”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “身份证编号” };
        GridView1.DataBind();
        sqlcon.Close();
        GridView1.Columns[3].Visible = false;//一开首东躲广西
        CheckBox1.Checked = false;//要是不那样后边的代码会把他True

    }

双击CheckBox1,在CheckedChanged方法里写上代码,最终代码如下:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
         GridView1.Columns[3].Visible=!
GridView1.Columns[3].Visible;
        
Response.Write(“GridView1的第四列以往的显得隐藏状态是:”+GridView1.Columns[3].Visible.ToString());
    }

注意:CheckBox1的AutoPostBack要True!

后台全部代码如下:

using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page 
{
    SqlConnection sqlcon;
    SqlCommand sqlcom; 
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState[“SortOrder”] = “身份证号码”;
            ViewState[“OrderDire”] = “ASC”;
            bind();
                   }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
    {
        string sqlstr = “delete from 飞狐工作室 where 身份证编号='” +
GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
        sqlcon = new SqlConnection(strCon);
        sqlcom = new SqlCommand(sqlstr,sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证编号='” 
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证号码” };
            GridView1.DataBind();
            sqlcon.Close();
            GridView1.Columns[3].Visible = false;
            CheckBox1.Checked = false;
        }
        protected void CheckBox1_CheckedChanged(object sender, EventArgs
    e)
        {
             GridView1.Columns[3].Visible=!
    GridView1.Columns[3].Visible;
            
    Response.Write(“GridView1的第⑥列以后的体现隐藏状态是:”+GridView1.Columns[3].Visible.ToString());
        }
    }

前台代码: <!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>GridView突显隐藏列 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body style=”font-size=12px”>
    <form id=”form1″ runat=”server”>
    <div>
                   <asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” />
                            <asp:BoundField DataField=”邮编”
HeaderText=”邮编” SortExpression=”邮编” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        <asp:CheckBox ID=”CheckBox1″ runat=”server”
AutoPostBack=”True” Font-Size=”12px”
            OnCheckedChanged=”CheckBox1_CheckedChanged”
Text=”展现隐藏家庭住址” /></div>
    </form>
</body>
</html>

 13.GridView弹出新页面/弹出制定大小地方新窗口:

效果图:
葡京网上娱乐场 26

方案一:不难的方式,新窗口不稳定大小
 <asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”邮编”
HeaderText=”邮编” SortExpression=”邮编” />
                            <asp:BoundField Data菲尔德=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:HyperLinkField HeaderText=”姓名”
Text=”姓名” DataNavigateUrlFields=”姓名”
DataNavigateUrlFormatString=”Default6.aspx?GoodsID={0}”
Target=”mainframe” NavigateUrl=”~/Default6.aspx” DataTextField=”姓名”
>
                    </asp:HyperLinkField>
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
DataNavigateUrl菲尔德s是链接的字段名,DataNavigateUrlFormatString是路径。

方案二:精确控制弹出窗口大小地方
<asp:HyperLinkColumn DataNavigateUrlField=”EmployeeID”
DataNavigateUrlFormatString=”javascript:varwin=window.open(‘detail.aspx?ID={0}’,null,’width=300,height=200′);window.Close();”
       DataTextField=”LastName”
HeaderText=”LastName”></asp:HyperLinkColumn>

行使的是组成javascript的window.open方法,关于window.open的参数网上有成都百货上千帖子,本站也有成都百货上千参阅
弹出窗口大全 http://blog.csdn.net/21aspnet/archive/2004/10/25/150231.aspx  
即可!

  14.GridView固定表头(不用javascript只用CSS!,很好用):

效果图:
葡京网上娱乐场 27

代码: <!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>GridView固定表头 清清月儿http://blog.csdn.net/21aspnet </title>
        <style> 
.Freezing 
   { 
    
   position:relative ; 
   table-layout:fixed;
   top:expression(this.offsetParent.scrollTop);   
   z-index: 10;
   }

.Freezing
th{text-overflow:ellipsis;overflow:hidden;white-space:
nowrap;padding:2px;}
</style> 
</head>
<body style=”font-size=12px”>
    <form id=”form1″ runat=”server”>
    <div style=”overflow-y: scroll; height: 200px;width:300px”
id=”dvBody”>
                   <asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px” OnRowCreated=”GridView1_RowCreated”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证号码”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField Data菲尔德=”邮编”
HeaderText=”邮编” SortExpression=”邮编” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” CssClass=”Freezing”/>
                    </asp:GridView>
        </div>

    </form>
</body>
</html>

用法:CSS设如上的体制,HeaderStyle加CssClass=”Freezing,套住GridView的Div设置高度大幅度<div style=”overflow-y: scroll; height: 200px;width:200px” >

15.GridView合并表头多重表头无错完美版(以联合3列3行举例)

效果图:
葡京网上娱乐场 28


后台代码:
using System;
using System.Data;
using System.Configuration;
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;
using System.Drawing;
public partial class _Default : System.Web.UI.Page 
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=西风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
            
        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证编号='” 
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 10 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证号码” };
            GridView1.DataBind();
            sqlcon.Close();
        }

//那里正是化解方案     protected void
GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.Header:
                //第2行表头
                TableCellCollection tcHeader = e.Row.Cells;
                tcHeader.Clear();
                tcHeader.Add(new TableHeaderCell());
                tcHeader[0].Attributes.Add(“rowspan”, “3”); //跨Row
                tcHeader[0].Attributes.Add(“bgcolor”, “white”);
                tcHeader[0].Text = “”;
                tcHeader.Add(new TableHeaderCell());
                //tcHeader[1].Attributes.Add(“bgcolor”, “Red”);
                tcHeader[1].Attributes.Add(“colspan”,
“6”); //跨Column
                tcHeader[1].Text =
“全体音讯</th></tr><tr>”;

                //第贰行表头
                tcHeader.Add(new TableHeaderCell());
                tcHeader[2].Attributes.Add(“bgcolor”,
“DarkSeaGreen”);
                tcHeader[2].Text = “身份证编号”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[3].Attributes.Add(“bgcolor”,
“LightSteelBlue”);
                tcHeader[3].Attributes.Add(“colspan”, “2”);
                tcHeader[3].Text = “基本消息”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[4].Attributes.Add(“bgcolor”,
“DarkSeaGreen”);
                tcHeader[4].Text = “福利”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[5].Attributes.Add(“bgcolor”,
“LightSteelBlue”);
                tcHeader[5].Attributes.Add(“colspan”, “2”);
                tcHeader[5].Text =
“联系格局</th></tr><tr>”;

                //第贰行表头
                tcHeader.Add(new TableHeaderCell());
                tcHeader[6].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[6].Text = “身份证号码”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[7].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[7].Text = “姓名”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[8].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[8].Text = “出生日期”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[9].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[9].Text = “薪水”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[10].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[10].Text = “家庭住址”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[11].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[11].Text = “邮编”;
                break;
        }
    }
}

前台:
<!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>GridView合并多重表头表头 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body >
    <form id=”form1″ runat=”server”>
    <div  >
                   <asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″ 
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px” OnRowCreated=”GridView1_RowCreated”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:BoundField DataField=”身份证号码”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            <asp:BoundField DataField=”出生日期”
HeaderText=”邮编”  />
                             <asp:BoundField DataField=”起薪”
HeaderText=”起薪”  />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField DataField=”邮编”
HeaderText=”邮编” />
                           
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        </div>

    </form>
</body>
</html>

16.GridView出色展现某一单元格(例如金额低于多少,分数不及格等)

效果图:
葡京网上娱乐场 29

缓解方案:首如若绑定后过滤  GridView1.DataBind();
        for (int i = 0; i <=
GridView1.Rows.Count – 1; i++)
        {
            DataRowView mydrv =
myds.Tables[“飞狐工作室”].DefaultView[i];
            string score = Convert.ToString(mydrv[“起薪”]);
            if (Convert.ToDouble(score) <
34297.00)//我们这里依据具体景况设置大概ToInt32等等
            {
                GridView1.Rows[i].Cells[4].BackColor =
System.Drawing.Color.Red;
            }
        }
        sqlcon.Close();

万事后台代码:

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

public partial class Default7 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();

        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证编号='”
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom = new SqlCommand(sqlstr, sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 10 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证编号” };
            GridView1.DataBind();
            for (int i = 0; i <=
    GridView1.Rows.Count – 1; i++)
            {
                DataRowView mydrv =
    myds.Tables[“飞狐工作室”].DefaultView[i];
                string score = Convert.ToString(mydrv[“起薪”]);
                if (Convert.ToDouble(score) < 34297.00)//大家那里依据具体意况设置大概ToInt32之类

            {
                GridView1.Rows[i].Cells[4].BackColor =
System.Drawing.Color.Red;
            }
        }
        sqlcon.Close();
    }
}

前台代码:

<!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 id=”Head1″ runat=”server”>
    <title>GridView卓绝展现某一单元格 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body >
    <form id=”form1″ runat=”server”>
    <div  >
                   <asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″ 
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            <asp:BoundField DataField=”出生日期”
HeaderText=”邮政编码”  />
                             <asp:BoundField DataField=”起薪”
HeaderText=”起薪”  DataFormatString=”{0:C}” HtmlEncode=”false”/>
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField Data菲尔德=”邮编”
HeaderText=”邮编” />
                           
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        </div>

    </form>
</body>
</html>

 17.GridView参加自动求和求平均值小计

效果图:葡京网上娱乐场 30
缓解方案:    
private double sum =
0;//取钦命列的数目和,你要依据具体意况对待或许您要处理的是int
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        
        if (e.Row.RowIndex >= 0)
        {
            sum += Convert.ToDouble(e.Row.Cells[6].Text);
        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[5].Text = “总薪给为:”;
            e.Row.Cells[6].Text = sum.ToString();
            e.Row.Cells[3].Text = “平均薪给为:”;
            e.Row.Cells[4].Text = ((int)(sum /
GridView1.Rows.Count)).ToString();
            
        }
    }

后台全体代码: using System;
using System.Data;
using System.Configuration;
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;
using System.Drawing;

public partial class Default7 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=西风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();

        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证号码='”
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom = new SqlCommand(sqlstr, sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证号码” };
            GridView1.DataBind();
            sqlcon.Close();
        }
        private double sum = 0;//取钦定列的数量和
        protected void GridView1_RowDataBound(object sender,
    GridViewRowEventArgs e)
        {
            
            if (e.Row.RowIndex >= 0)
            {
                sum += Convert.ToDouble(e.Row.Cells[6].Text);
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[5].Text = “总薪给为:”;
                e.Row.Cells[6].Text = sum.ToString();
                e.Row.Cells[3].Text = “平均薪酬为:”;
                e.Row.Cells[4].Text = ((int)(sum /
    GridView1.Rows.Count)).ToString();
                
            }
        }
    }
    前台:唯一的花头正是安装ShowFooter=”True” ,不然默许表头为隐藏的!
    <asp:GridView ID=”GridView1″ runat=”server”   
    AutoGenerateColumns=”False” CellPadding=”3″ 
    OnRowEditing=”GridView1_RowEditing”
                            OnRowUpdating=”GridView1_RowUpdating”
    OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
    BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
    Font-Size=”12px” OnRowDataBound=”GridView1_RowDataBound”
    ShowFooter=”True”  >
                            <FooterStyle BackColor=”White”
    ForeColor=”#000066″ />
                            <Columns>
                                <asp:CommandField HeaderText=”编辑”
    ShowEditButton=”True” />
                                <asp:BoundField DataField=”身份证编号”
    HeaderText=”编号” ReadOnly=”True” />
                                <asp:BoundField DataField=”姓名”
    HeaderText=”姓名”  />
                                <asp:BoundField DataField=”出生日期”
    HeaderText=”邮政编码”  />
                                <asp:BoundField DataField=”家庭住址”
    HeaderText=”家庭住址”  />
                                <asp:BoundField DataField=”邮编”
    HeaderText=”邮编” />
                                <asp:BoundField DataField=”起薪”
    HeaderText=”起薪”  />
                               
                            </Columns>
                            <RowStyle ForeColor=”#000066″ />
                            <SelectedRowStyle BackColor=”#669999″
    Font-Bold=”True” ForeColor=”White” />
                            <PagerStyle BackColor=”White”
    ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
    DataGridFixedHeader”/>
                            <HeaderStyle BackColor=”#006699″
    Font-Bold=”True” ForeColor=”White” />
                        </asp:GridView>

 

 18.GridView**多少导入Excel/Excel数据读入GridView**

效果图: 葡京网上娱乐场 31

化解方案:
页面增加2个按钮,单击事件添加如下方法:
protected void Button1_Click(object sender, EventArgs e)
    {
        Export(“application/ms-excel”, “学生成绩报表.xls”);
    }

    private void Export(string FileType, string FileName)
    {
        Response.Charset = “GB2312”;
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AppendHeader(“Content-Disposition”,
“attachment;filename=” + HttpUtility.UrlEncode(FileName,
Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
//如果没有下边方法会报错类型“GridView”的控件“GridView1”必须放在具有
runat=server 的窗体标记内
    public override void VerifyRenderingInServerForm(Control
control)
    {
    }
还有由于是文件操作所以要引入名称空间IO和Text

后台代码: using System;
using System.Data;
using System.Configuration;
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;
using System.Drawing;
using System.IO;
using System.Text;
public partial class Default7 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();

        }
    }
    
    public void bind()
    {
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “飞狐工作室”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “身份证编号” };
        GridView1.DataBind();
        sqlcon.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Export(“application/ms-excel”, “学生成绩报表.xls”);
    }

    private void Export(string FileType, string FileName)
    {
        Response.Charset = “GB2312”;
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AppendHeader(“Content-Disposition”,
“attachment;filename=” + HttpUtility.UrlEncode(FileName,
Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
    
}

前台
<asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″  
                         BackColor=”White” BorderColor=”#CCCCCC”
BorderStyle=”None” BorderWidth=”1px” Font-Size=”12px”   >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            <asp:BoundField DataField=”出生日期”
HeaderText=”邮编”  />
                            <asp:Bound菲尔德 Data菲尔德=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField Data菲尔德=”邮编”
HeaderText=”邮政编码” />
                            <asp:BoundField DataField=”起薪”
HeaderText=”起薪”  />
                           
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        <asp:Button ID=”Button1″ runat=”server”
OnClick=”Button1_Click” Text=”导出” />

读取Excel数据的代码:这一个非常的粗略的
private DataSet CreateDataSource()
    {
        string strCon;
        strCon = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” +
Server.MapPath(“excel.xls”) + “; Extended Properties=Excel 8.0;”;
        OleDbConnection olecon = new OleDbConnection(strCon);
        OleDbDataAdapter myda = new OleDbDataAdapter(“SELECT * FROM
[Sheet1$]”, strCon);
        DataSet myds = new DataSet();
        myda.Fill(myds);
        return myds;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = CreateDataSource();
        GridView1.DataBind();
    }