ASP.NET MVC搭建筑类后台UI框架—8、将View中甄选的数量行中的片段数据传到Controller中

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**

目录

**

  1. ASP.NET
    MVC搭建筑项目后台UI框架—1、后台主框架
  2. ASP.NET
    MVC搭建筑项目后台UI框架—2、菜单特效
  3. ASP.NET
    MVC搭建筑项目后台UI框架—3、面板折叠和展开
  4. ASP.NET
    MVC搭建筑项目后台UI框架—4、tab多页签支持
  5. ASP.NET
    MVC搭建筑项目后台UI框架—5、Demo演示Controller和View的交互
  6. ASP.NET
    MVC搭建筑类后台UI框架—6、客户保管(添加、修改、查询、分页)
  7. ASP.NET
    MVC搭建筑项目后台UI框架—7、统计报表
  8. ASP.NET
    MVC搭建筑项目后台UI框架—8、将View中选取的数目行中的有些数据传到Controller中
  9. ASP.NET
    MVC搭建筑类后台UI框架—9、服务器端排序

1.GridView无代码分页排序

图片 1

效果图:
图片 2
1.AllowSorting要为True,aspx代码中凡AllowSorting=”True”;
2.默认1页10漫漫,如果只要修改每页条数,修改PageSize即可,在aspx代码中凡是PageSize=”12″。
3.默认的凡只是为排序的,右击GridView弹出“属性”,选择AllowSorting为True即可。

图片 3图片 4

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

现今,有一个要求,我急需将表格中选中行的数遭到之一样有的污染直接招至控制器中,然后保留及另外一张表中。一开始,我哪怕想到以前台使用ajax构造json数据,然后控制器直接通过list接收。

效果图:
图片 5

当选界面被的尽,然后点击“批量补偿加到月结表”,弹出一个对话框,这个对话框的月份列表为当下增选数据行中结账日期所在月份、以及前一个月同后一个月份,选择月后,将选取的月度,以及界面选中的行中的数并传到控制器中去。我发觉网上挺少发这种以前台构造复杂json,传递让控制器的,更多之是从控制器调用Json方法将后台数据易为json格式,然后展示暨前台,所以自己就将贯彻方式记录下来,希望会给大家提供参考。

后台代码: 卿得用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;

控制器Reconciliation代码:

public partial class _Default : System.Web.UI.Page 
{

        /// <summary>
        /// 添加月结表
        /// </summary>
        /// <param name="no"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public ActionResult AddMonthPayOff(DateTime payOffDate)
        {
            ViewBag.PreMonthStr = payOffDate.AddMonths(-1).Month + "月";
            ViewBag.MonthStr = payOffDate.Month + "月";
            ViewBag.NextMonthStr = payOffDate.AddMonths(1).Month + "月";

            ViewBag.PreYearMonth = payOffDate.AddMonths(-1);
            ViewBag.YearMonth = payOffDate;
            ViewBag.NextYearMonth = payOffDate.AddMonths(1);
            return View();
        }

        /// <summary>
        /// 添加月结表       
        /// </summary>
        /// <param name="data"></param>
        /// <param name="isNeglect">是否忽视异常</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddMonthPayOff(List<MonthPayOffModel> data, bool isNeglect, DateTime payOffMonth)
        {
            string message = string.Empty;
            var dealdata = data.Select(a => new MonthPayOffData()
            {
                MonthPayTime = payOffMonth,
                ReconcileTime = a.ReconcileTime,
                PreTotalCostFee = a.PreTotalCostFee,
                TotalCostFee = a.TotalCostFee,
                PreInComeFee = a.PreInComeFee,
                InComeFee = a.InComeFee,
                TotalMargin = a.TotalMargin,
                LoadBillBy = LoadBillInCome.GetByLoadBillNum(a.LoadBillNum)
            }).ToList();
            if (MonthPayOff.AddMonthPay(isNeglect, dealdata, payOffMonth, out message))
            {
                return Json(new { IsSuccess = true, Message = string.Format("共计:{0}个提单添加到月结", data.Count) });
            }
            else
            {
                return Json(new { IsSuccess = false, Message = message, IsPoint = message.Substring(0, 2) == "提醒" ? true : false });
            }
        }

//清清月儿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();
    }

视图AddMonthPayOff:

//删除
    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();
    }

@{
    ViewBag.Title = "AddMonthPayOff";
    Layout = null;
}
@Html.Raw(ViewBag.Msg)
<script src="~/Scripts/jquery-1.8.3.min.js"></script>
<link href="~/Content/main.css" rel="stylesheet" />
<style type="text/css">
    table tr {
        height:24px;
    }
</style>
<script type="text/javascript">
    function selectpayMonth() {
        var list = $('input:radio[name="monthPayOff"]:checked').val();
        if (list == null) {
            return false;
        }
        else {
            frameElement.api.opener.postSelectData(list,false);
        }
    }
</script>

        @using (Html.BeginForm("AddMonthPayOff", "Reconciliation", FormMethod.Post, new { @clase = "form-inline", @role = "form", name = "from1" }))
        {
            <table style="text-align:center;width:190px;margin-top:10px;">
                <tr><td style="width:190px;"><input type="radio" name="monthPayOff"  value="@ViewBag.PreYearMonth"/>  @ViewBag.PreMonthStr</td></tr>
                <tr><td><input type="radio" name="monthPayOff" value="@ViewBag.YearMonth"/>  @ViewBag.MonthStr</td></tr>
                <tr><td><input type="radio" name="monthPayOff" value="@ViewBag.NextYearMonth"/>  @ViewBag.NextMonthStr</td></tr>
                <tr><td><input type="button" value="确定" onclick="selectpayMonth()" class="popbtn1 mg" style="text-align:center;margin:10px 0 10px 10px !important;">
                @*<input type="button" value="关闭" class="popbtn3 mg2" onclick="frameElement.api.opener.addDG.close();" />*@</td> 
              </tr>
            </table>
        }

//更新
    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()

主界面视图LoadBill:这里主要记录选中的推行数据,然后以那个结构成json格式,通过ajax传递让控制器,注意这里构造之json数据,和控制器中对应之收参数是同样的。

  • “‘,字段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();
        }
   //添加到月结表 提单号,结算月份、包裹数、总成本、总收入、总毛利
    function AddMonthlyBalance(id, date, ExpressCount, CostTotalFee, InComeTotalFee, GrossProfitRate) {
        if (date == '') {
            $.dialog.alert("提货单“"+id+"”数据未导入成本数据,且未清关");
            return false;
        }
        var d = { isNeglect: false, data: [{"LoadBillNum": id, "ReconcileTime": date, "PreTotalCostFee": CostTotalFee,"TotalCostFee": CostTotalFee,"PreInComeFee":
 InComeTotalFee,"InComeFee": InComeTotalFee,"TotalMargin": GrossProfitRate }] };
        selectData = JSON.stringify(d);
        addDG = $.dialog({
            id: 'AddMonthPayList',
            title: '添加到月结表',
            width: 200,
            height: 150,
            content: "url:/Reconciliation/AddMonthPayOff?payOffDate="+date,
            close: true,
            btnBar: false,
            max: false,
            min: false,
            lock: true
        })
    }

//取消
    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();
    }
}

@{
    ViewBag.Title = "提货单对账";
}
<link href="~/libs/DataTables-1.10.6/media/css/jquery.dataTablesNew.css" rel="stylesheet" />
<script src="~/libs/DataTables-1.10.6/media/js/jquery.dataTables.min.js"></script>
<script src="~/Scripts/DataTablesExt.js"></script>
<script src="~/libs/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript">
    var selectData; //选择行数据
    $(function () {
        var table = $("#table_local").dataTable({
            bProcessing: true,
            "scrollY": table_h,
            "scrollX": $(document).width(),
            "scrollCollapse": "true",
            "dom": 'tr<"bottom"lip><"clear">',
            "bServerSide": true,                    //指定从服务器端获取数据  
            "iDisplayLength": 10,
            sServerMethod: "POST",
            showRowNumber:true,
            sAjaxSource: "@Url.Action("LoadBillList", "Reconciliation")",
            //"initComplete": function (data, args) {
            //    //getTotal(args);
            //    var arr = new Array(7,8,9,10,11,14,15,16,17,18); //页面一加载隐藏的列
            //    controlColumnShow(table, arr,false);
            //},
            "fnServerParams": function (aoData) {  //查询条件
                aoData.push(
                    { "name": "CusName", "value": $("#CusName").val() },
                    { "name": "LoadBillNum", "value": $("#LoadBillNum").val() },
                    { "name": "CompletionSTime", "value": $("#CompletionSTime").val() },
                    { "name": "CompletionETime ", "value": $("#CompletionETime").val() }
                     );
            },
            //跟数组下标一样,第一列从0开始,这里表格初始化时,第四列默认降序
            "order": [[ 2, "asc" ]],
            columns: [
               {
                   "data": "ID", orderable: false,width:"60",
                   "render": function (data, type, row, meta) {
                       return " <input id='cbx" + data + "' type='checkbox' onclick='controlSelectAll(" + data + ")' class='cbx' value='" + data + "'/>  " + row.Index;
                   }
               },                                                      
                { "data": "CusName" }, //客户名称
                { "data": "LoadBillNum" },//提单号
                { "data": "FeeWeight", orderable: false }, //提单包裹重量
                { "data": "ExpressCount", orderable: false }, //提单包裹数量
                { "data": "CompletionTime" }, //清关完成时间
                { "data": "GroundHandlingFee", visible: false },//邮政地勤费
                { "data": "CostStoreFee", visible: false },//邮政仓租
                {
                    "data": "CostExpressFee", orderable: false, visible: false, "render": function (data, type, row, meta) {
                        var css = "";
                        if (row.IsReal==0) {
                            css = " class='preColor'";
                        }
                        var re = "<div" + css + ">" + data + "</div>";
                        return re;
                    }
                },//邮政邮资
                {
                    "data": "CostOperateFee", orderable: false, visible: false, "render": function (data, type, row, meta) {
                        var css = "";
                        if (row.IsReal == 0) {
                            css = " class='preColor'";
                        }
                        var re = "<div" + css + ">" + data + "</div>";
                        return re;
                    }
                },//邮件处理费
                { "data": "CostOtherFee", visible: false },//邮政其他费用
                { "data": "CostTotalFee" },//邮政总成本
                { "data": "CostStatus" },//邮政结算状态
                { "data": "InComeLoadFee", visible: false },//客户提货费
                { "data": "InComeStoreFee", visible: false },//客户仓租
                { "data": "InComeExpressFee", visible: false },//客户运费
                { "data": "InComeOperateFee", visible: false },//客户操作费
                { "data": "InComeOtherFee", visible: false },//其他费用
                { "data": "InComeTotalFee" },//总收入
                { "data": "InComeStatus",orderable: false ,width:"90"},//结算状态
                {
                    "data": "TotalGrossProfit", orderable: false, "render": function (data, type, row, meta) {
                        var css = "";
                        if (data < 0) {
                            css=" class='numberColor'";
                        }
                        var re = "<div"+css+">"+data+"</div>";
                        return re;
                    }
                },//总毛利
                {
                    "data": "GrossProfitRate", orderable: false, "render": function (data, type, row, meta) {
                        var css = "";
                        if (data < 0) {
                            css = " class='numberColor'";
                        }
                        var re = "<div" + css + ">" + data + "%</div>";
                        return re;
                    }
                },//毛利率
                { "data": "Status",width: "120", orderable: false },//对账单状态
                {
                    "data": "LoadBillNum", orderable: false, width: "160", "render": function (data, type, row, meta) {
                        var re = "<div style='text-align:center'><a style='visibility:visible' onclick='openDetail(" + data + ")'>明细</a>&nbsp;&nbsp;";
                        if (row.IsAddMonthPayOff == 0) {
                            var reconcileDate = row.ReconcileDate == '' ? row.CompletionTime : row.ReconcileDate;
                            re += "<a style='visibility:visible' name='addMonthPayOff' onclick='AddMonthlyBalance(\"" + data + "\",\"" + reconcileDate + "\","
                                + row.ExpressCount + "," + row.CostTotalFee + "," + row.InComeTotalFee + "," + row.TotalGrossProfit + ")'>添加到月结表</a>";
                        }
                        return re+"</div>";
                    }
                }//操作
            ],
            paging: true,//分页
            ordering: true,//是否启用排序
            searching: true,//搜索
            language: {
                "sProcessing": "处理中...",
                lengthMenu: '每页显示:<select class="form-control input-xsmall">' + '<option value="10">10</option>' + '<option value="20">20</option>' + '<option value="30">30</option>'
                    + '<option value="50">50</option>' + '<option value="100">100</option>' + '<option value="150">150</option>' + '<option value="200">200</option>' 
+ '<option value="250">250</option>',//左上角的分页大小显示。
                search: '搜索:',//右上角的搜索文本,可以写html标签

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

                zeroRecords: "暂无记录",//table tbody内容为空时,tbody的内容。
                //下面三者构成了总体的左下角的内容。
                info: "总共 (_PAGES_) 页,显示 _START_ -- _END_ ,共 (_TOTAL_) 条",//左下角的信息显示,大写的词为关键字。初始_MAX_ 条 
                infoEmpty: "0条记录",//筛选为空时左下角的显示。
                infoFiltered: ""//筛选之后的左下角筛选提示,
            },
            pagingType: "full_numbers"//分页样式的类型
        });
        //new $.fn.dataTable.FixedColumns(table);
        //设置选中行样式
        $('#table_local tbody').on('click', 'tr', function () {
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
            }
            else {
                table.$('tr.selected').removeClass('selected');
                $(this).addClass('selected');
            }
        });
        //展开折叠列
        $("#imgIncome").click(function () {
            var url = $("#imgIncome").attr("src");
            var arr = new Array(8, 9, 10, 6,7);
            if (url == "icon_9.png") {
                controlColumnShow(table, arr, true);
                $("#imgIncome").attr("src", "icon_10.png");
            }
            else {
                controlColumnShow(table, arr, false);
                $("#imgIncome").attr("src", "icon_9.png");
            }

        });
        //收入展开折叠
        $("#imgCost").click(function () {
            var url = $("#imgCost").attr("src");
            var arr = new Array(14,15,16, 17, 13);
            if (url == "icon_9.png") {
                controlColumnShow(table, arr, true);
                $("#imgCost").attr("src", "icon_10.png");
            }
            else {
                controlColumnShow(table, arr, false);
                $("#imgCost").attr("src", "icon_9.png");
            }
        });
        //获取批量选择行
        $("#btnAddMonthPayOffList").click(function () {
            var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行,nTrs[i]表示第i行tr对象
            var row;
            selectData = "{'data': [";
            var selectCounts = 0;
            var date;
            for (var i = 0; i < nTrs.length; i++) {
                if ($(nTrs[i])[0].cells[0].children[0].checked) {
                    row = table.fnGetData(nTrs[i]);//fnGetData获取一行的数据
                    selectCounts++;
                    var tempdate = row.ReconcileDate == '' ? row.CompletionTime : row.ReconcileDate;
                    if (tempdate == '') {
                        $.dialog.alert("提货单“" + row.LoadBillNum + "”数据未导入成本数据,且未清关");
                        return false;
                    }
                    //当时间不统一时,获取最大时间
                    if (date == undefined || new Date(tempdate.replace("-", "/").replace("-", "/")) > new Date(date.replace("-", "/").replace("-", "/"))) {
                        date = tempdate;
                    }
                    selectData += "{'LoadBillNum':'" + row.LoadBillNum + "','ReconcileTime':'" + tempdate + "','PreTotalCostFee':'" + row.CostTotalFee
                        +"','TotalCostFee':'"+row.CostTotalFee+ "','PreInComeFee':'" + row.InComeTotalFee +"','InComeFee':'"+row.InComeTotalFee+ "','TotalMargin':'" + row.TotalGrossProfit + "'},";
                }
            }
            selectData = selectData.substring(0, selectData.length - 1)
            selectData += "]}";
            if (selectCounts < 1) {
                $.dialog.alert("请先选择要添加的数据行!");
                return false;
            }
            AddMonthlyBalanceList(date);
        });
    });
    function reloadList() {
        var tables = $('#table_local').dataTable().api();//获取DataTables的Api,详见 http://www.datatables.net/reference/api/
        tables.ajax.reload(function () {
            //var json = tables.context[0].json;
            //getTotal(json);
        }, false);
    }
    //统计
    function getTotal(json) {
        if (json) {
            if (json.TotalWeight) {
                $("#spnTotalWeight").html(json.TotalWeight);
                $("#spnTotalWayBillFee").html(json.TotalWayBillFee);
                $("#spnTotalProcessingFee").html(json.TotalProcessingFee);
                $("#spnTotalExpressFee").html(json.TotalExpressFee);
                $("#spnTotalOperateFee").html(json.TotalOperateFee);
                $("#spnSumWayBillProfit").html(json.SumWayBillProfit);
                $("#spnSumTotalProfit").html(json.SumTotalProfit);
            }
        }
    }
    //控制指定定列的隐藏和显示(table,列索引数组,隐藏or显示:true,false)
    function controlColumnShow(table, arr,tag) {
        for (var i = 0; i < arr.length; i++) {
            table.fnSetColumnVis(arr[i],tag);
        }
    }
    var addDG;
    var payOffMonth;
    //添加到月结表 提单号,结算月份、包裹数、总成本、总收入、总毛利
    function AddMonthlyBalance(id, date, ExpressCount, CostTotalFee, InComeTotalFee, GrossProfitRate) {
        if (date == '') {
            $.dialog.alert("提货单“"+id+"”数据未导入成本数据,且未清关");
            return false;
        }
        var d = { isNeglect: false, data: [{"LoadBillNum": id, "ReconcileTime": date, "PreTotalCostFee": CostTotalFee,"TotalCostFee": CostTotalFee,"PreInComeFee": InComeTotalFee,
"InComeFee": InComeTotalFee,"TotalMargin": GrossProfitRate }] };
        selectData = JSON.stringify(d);
        addDG = $.dialog({
            id: 'AddMonthPayList',
            title: '添加到月结表',
            width: 200,
            height: 150,
            content: "url:/Reconciliation/AddMonthPayOff?payOffDate="+date,
            close: true,
            btnBar: false,
            max: false,
            min: false,
            lock: true
        })
    }
    //批量添加到月结表
    function AddMonthlyBalanceList(date) {
        addDG = $.dialog({
            id: 'AddMonthPay',
            title: '添加到月结表',
            width: 200,
            height: 150,
            content: "url:/Reconciliation/AddMonthPayOff?payOffDate=" + date,
            close: true,
            btnBar: false,
            max: false,
            min: false,
            lock: true
        })
    }
    //隐藏弹出框
    function hidePublishWin(msg, result, isStay) {
        var icon = "success.gif";
        if (result == "False") {
            icon = "error.gif";
        }
        $.dialog({
            title: "提示",
            icon: icon,
            titleIcon: 'lhgcore.gif',
            content: msg,
            lock: true,
            ok: true
        });
        if (result != "False") {
            if (addDG) {
                addDG.close();
            }
            if (isStay == 0) {
                reloadList();
            }
            else {
                reloadListNew();
            }
        }
    }
    //传递选择的行数据
    function postSelectData(payOffMonth, isNeglect) {
        //JSON.parse
        //var json = JSON.stringify(selectData);
        //var json = selectData;//JSON.parse(selectData);
        selectData = selectData.substring(0, selectData.length - 1) + ",'payOffMonth':'" + payOffMonth + "','isNeglect':"+isNeglect+"}";
        $.ajax({
            url: '/Reconciliation/AddMonthPayOff',
            type: 'POST',
            dataType: 'json',
            data: selectData,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (isNeglect==false) {
                    addDG.close();
                }
                if (!data.IsSuccess && data.IsPoint) {
                    $.dialog.confirm(data.Message, function () { postSelectData(payOffMonth, true); });
                }
                else {
                    $.dialog.alert(data.Message);
                }
            }
        });
    }
</script>
<div class="areabx clear">
    @using (Html.BeginForm("List", null, FormMethod.Get, new { @clase = "form-inline", @role = "form" }))
    {
        <div id="divSearch">
        @*<div class="areabx_header">@ViewBag.Title</div>*@
        <ul class="formod mgt10">
            <li>客户名:@Html.TextBox("CusName","",new { @class = "trade-time wid153" })</li>
            <li>提单号:@Html.TextBox("LoadBillNum","", new { @class = "trade-time" })</li>
        </ul>
        <ul class="formod mgt10">
            <li>清关完成时间:@Html.TextBox("CompletionSTime", "", new { @class = "trade-time wid153", @onClick = "WdatePicker({maxDate:'#F{$dp.$D(\\'CompletionETime\\')}'})" })</li>
            <li>—  @Html.TextBox("CompletionETime", "", new { @class = "trade-time wid153", 
@onClick =  "WdatePicker({minDate:'#F{$dp.$D(\\'CompletionSTime\\')}'})"  })</li>
        </ul>
        <div class="botbtbx pdb0">
            <input type="button" value="查询" id="btnSearch" onclick="reloadList();" class="btn btn-primary" />
            <input type="button" id="btnAddMonthPayOffList" value="批量添加到月结表" class="btn btn-primary"/>
        </div>
            </div>
    }
    <div class="tob_box mgt15">
        <table id="table_local" class="display" cellspacing="0" cellpadding="0" border="0" style="width: 100%;">
            <thead>
                <tr>
                    <th rowspan="2"><input type='checkbox' id='chkAllColl' onclick='selectAll()' />序号</th>
                    <th rowspan="2">客户简称</th>
                    <th rowspan="2">提单号</th>
                    <th rowspan="2">提单包裹重量(KG)</th>
                    <th rowspan="2">提单包裹数量</th>
                    <th rowspan="2">清关完成时间</th>
                    <th colspan="7">成本<img id="imgIncome" src="icon_9.png"  alt="收起/展开" title="收起/展开"/></th>
                    <th colspan="7">收入<img id="imgCost" src="icon_9.png" alt="收起/展开" title="收起/展开"/></th>
                    <th colspan="2">毛利</th>
                    <th rowspan="2">对账单状态</th>
                    <th rowspan="2">操作</th>
                </tr>
                <tr>
                    <th>邮政地勤费</th>
                    <th>邮政仓租</th>
                    <th>邮政邮资</th>
                    <th>邮件处理费</th>
                    <th>邮政其他费用</th>
                    <th>邮政总成本</th>
                    <th>邮政结算状态</th>
                    <th>客户提货费</th>
                    <th>客户仓租</th>
                    <th>客户运费</th>
                    <th>客户操作费</th>
                    <th>其他费用</th>
                    <th>总收入</th>
                    <th>结算状态</th>
                    <th>总毛利</th>
                    <th>毛利率</th>
                </tr>
            </thead>
            @*<tfoot>
                <tr>
                    <td>总计</td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
            </tfoot>*@
        </table>
    </div>
</div>

前台要代码:                             … …
<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:BoundField DataField=”身份证号码”
HeaderText=”用户ID” 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>

MonthPayOffModel模型类:

3.GridView正反双向排序: 效果图:点姓名各2次的排序,点外为同样可以。
图片 6图片 7
后台代码:
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
{

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Site.Models
{
    public class MonthPayOffModel
    {
        /// <summary>
        /// 对账时间
        /// </summary>
        public DateTime ReconcileTime { get; set; }
        /// <summary>
        /// 预计总成本
        /// </summary>
        public decimal PreTotalCostFee{get;set;}
        /// <summary>
        /// 真实总成本
        /// </summary>
        public decimal TotalCostFee{get;set;}
        /// <summary>
        /// 预计总收入
        /// </summary>
        public decimal PreInComeFee{get;set;}
        /// <summary>
        /// 真实总收入
        /// </summary>
        public decimal InComeFee { get; set; }
        /// <summary>
        /// 总毛利
        /// </summary>
        public decimal TotalMargin { get; set; }
        /// <summary>
        /// 提单号
        /// </summary>
        public string LoadBillNum { get; set; }
    }
}

//清清月儿的博客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();
    }

js控制全选反选

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

//监听每一行的复选框,控制全选、反选按钮  
function controlSelectAll(i) {
    var tblName, cbkAll; //Gridview ID ,全选框ID  
    var tblName = "table_local";
    var cbkAll = "chkAllColl";
    var id = "#cbx" + i;
    //点击复选框选中行
    //if ($(id)[0].checked == true) {
    //    $(id).parent().parent().addClass('selected');
    //    $(id).parent().parent().siblings().removeClass('selected');
    //} else {
    //    $(id).parent().parent().siblings().removeClass('selected');
    //    $(id).parent().parent().removeClass('selected');
    //}
    var chks = getCheckbox(tblName);
    var count = 0;
    for (var i = 0; i < chks.length; i++) {
        if (chks[i].checked == true) {
            count++;
        }
    }
    if (count < chks.length) {
        document.getElementById(cbkAll).checked = false;
    }
    else {
        document.getElementById(cbkAll).checked = true;
    }
}
//全选反选
function selectAll() {
    if ($("#chkAllColl").attr("checked")) {//如果全选的checkbox为选中状态时
        $("#table_local input").attr("checked", "checked");//其他的checkbox全部勾选
        //$("#table_local tbody tr").addClass('selected');
    }
    else {//如果全选的checkbox为选非中状态时
        $("#table_local input").attr('checked', false);//其他的checkbox全部取消勾选
        //$("#table_local tbody tr").removeClass('selected');
    }
}

前台要代码: <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 DataField=”身份证号码”
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>

 

 

 代码很多,不要给吓到了,其实也生粗略,难点在在怎样组织json,然后被控制器自动接到并机关分析成List<Model>形式。这里以了js的JSON.stringify(d)方法,注意json字符串里面的性能和值都加引号。

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

效果图:
图片 8

后台代码: 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:TemplateField
HeaderText=”员工性别”>
                                <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结合:

效果图:
图片 9

后台代码:

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某同执行时转该行的背景色方法同样:

效果图:
图片 10
做法:
双击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: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>
    
    </div>
    </form>
</body>
</html>

7.鼠标移到GridView某一样实践时转该行的背景色方法二:

效果图:
图片 11

做法:和地方的一律就是是代码不同 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实现删除时弹出肯定对话框:

效果图:
图片 12

贯彻方式: 双击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实现自动编号:

效果图:
图片 13

心想事成方式: 双击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-未格式化前
图片 14
图2-格式化后
图片 15
解决方法:

当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填充的4独字符宽的字段中显得整数;
{0:000.0}四放弃五副小数点保留第几各中数字;
{0:N2}小数点保留2位有效数字;{0:N2}%   小数点保留2位有效数字加百分号;
{0:D}长日期;{0:d}短日期;{0:yy-MM-dd}   例如07-3-25;;{0:yyyy-MM-dd} 
例如2007-3-25

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

效果图:
图片 16
缓解方式:数据绑定后过滤每一样实行即可
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一般换行与强制换行:

效果图:
图片 17
率先设置<asp:BoundField DataField=”家庭住址” HeaderText=”家庭住址” 
ItemStyle-Width=”100″ />
gridview里有同排绑定的多少好丰富,显示的早晚以一行里面显示,页面拉得稀方便。
因是连连英文段为一个总体招的,在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显示隐藏某平等排: 论方案也月儿独创,不同让网上其他方法,我看之所以一个CheckBox更人性化,这样可以隐藏不必要的排列,让用户自己选择得出现的排,在拍卖多排时即是一个怪好之化解方案!

效果图:
图1-开始
图片 18
祈求2-点击显示的CheckBox后
图片 19

釜底抽薪方案: 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的第4列本底来得隐藏状态是:”+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的第4排本底亮隐藏状态是:”+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弹出新页面/弹来制定大小位置新窗口:

效果图:
图片 20

方案一:简单的方,新窗口不定点大小
 <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 DataField=”家庭住址”
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>
DataNavigateUrlFields是链接的配段名,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!,很好用):

效果图:
图片 21

代码: <!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 DataField=”邮政编码”
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行比方)

效果图:
图片 22


后台代码:
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:
                //第一执表头
                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突出显示有平单元格(例如金额低于多少,分数不合格等)

效果图:
图片 23

釜底抽薪方案:主要是绑定后过滤  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 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>

 17.GridView加入自动求和呼吁平均值小计

效果图:图片 24
化解方案:    
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**

效果图: 图片 25

解决方案:
页面增加一个按钮,单击事件添加如下方法:
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: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>
        <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();
    }