当前位置: 首页 > news >正文

C#操作GridView控件绑定数据实例详解(二)

上文实现的GridView控件:

(一)翻页功能

翻页内容,主要实现的是该控件下面,上下翻页,跳转到指定页面。 

翻页功能要注意前台页面下面这段代码中的相关命令:

<PagerTemplate  >
                                                当前第:
                                                 <%--//((GridView)Container.NamingContainer)就是为了得到当前的控件--%>
                                                <asp:Label ID="LabelCurrentPage" runat="server" Text="<%# ((GridView)Container.NamingContainer).PageIndex + 1 %>"></asp:Label>
                                                页/共
                                                <%--//得到分页页面的总数--%>
                                                <asp:Label ID="LabelPageCount" runat="server" Text="<%# ((GridView)Container.NamingContainer).PageCount %>"></asp:Label>
                                                页
                                                <%--//如果该分页是首分页,那么该连接就不会显示了.同时对应了自带识别的命令参数CommandArgument--%>
                                                <asp:LinkButton ID="LinkButtonFirstPage" runat="server" CommandArgument="First" CommandName="Page" BackColor="#2196f3" ForeColor="White"
                                                    Visible='<%#((GridView)Container.NamingContainer).PageIndex != 0 %>'>首页</asp:LinkButton>
                                                <asp:LinkButton ID="LinkButtonPreviousPage" runat="server" CommandArgument="Prev"  BackColor="#2196f3"  ForeColor="White"
                                                    CommandName="Page" Visible='<%# ((GridView)Container.NamingContainer).PageIndex != 0 %>'>上一页</asp:LinkButton>
                                                <%--//如果该分页是尾页,那么该连接就不会显示了--%>
                                                <asp:LinkButton ID="LinkButtonNextPage" runat="server" CommandArgument="Next" CommandName="Page" BackColor="#2196f3" ForeColor="White"
                                                    Visible='<%# ((GridView)Container.NamingContainer).PageIndex != ((GridView)Container.NamingContainer).PageCount - 1 %>'>下一页</asp:LinkButton>
                                                <asp:LinkButton ID="LinkButtonLastPage" runat="server" CommandArgument="Last" CommandName="Page" BackColor="#2196f3" ForeColor="White"
                                                    Visible='<%# ((GridView)Container.NamingContainer).PageIndex != ((GridView)Container.NamingContainer).PageCount - 1 %>'>尾页</asp:LinkButton>
                                                转到第
                                               <%-- <asp:TextBox ID="txtNewPageIndex" CssClass="pagecount" runat="server" Width="40px" Text='<%# ((GridView)Container.Parent.Parent).PageIndex + 1 %>' />页--%>
                                                 <asp:TextBox ID="Pagenum" CssClass="pagenum" runat="server" Width="20px" Text='<%# ((GridView)Container.Parent.Parent).PageIndex + 1 %>' />页                                               
                                                <%--//这里将CommandArgument即使点击该按钮e.newIndex 值为3 --%>
                                                <asp:LinkButton ID="btnGo" runat="server" CausesValidation="False" CommandArgument="-2"  CssClass="pagejump"  CommandName="Jump" Text="跳转" />
                                            </PagerTemplate>

对应的,加入翻页控件的代码:

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
GridView1.PageIndex = e.NewPageIndex;
            ReturnCurBindData();
            TextBox txt = (TextBox)GridView1.BottomPagerRow.FindControl("Pagenum");
            txt.Text = (GridView1.PageIndex + 1).ToString();


        }

ReturnCurBindData()方法的代码,是判断是否有搜索关键字或者分页,来重新绑定数据的。

private void ReturnCurBindData()
        {
            if (txt_key.Text.Trim() != "")//当有搜索关键词时,根据关键词绑定数据
            {
                this.GridView1.DataSource = SoftToolsDAL.SelectSoftToolsBySearchKey(txt_key.Text.Trim());//SoftToolsDal.SelectAllSoftToolsByClassid(int.Parse(selectvaule));
                this.GridView1.DataBind();
            }
            else
            {
                //如果没有关键词,看是否按分类来绑定。

                if (ddl_class.SelectedValue != "0")
                {
                    this.GridView1.DataSourceID = null;
                    string selectvaule = this.ddl_class.SelectedValue;
                    if (selectvaule == "0")
                    {
                        Response.Redirect("DataBindProduce.aspx");
                    }
                    else
                    {
                        this.GridView1.DataSource = SoftToolsDAL.SelectAllSoftToolsByClassid(int.Parse(selectvaule));
                        this.GridView1.DataBind();
                    }

                }
                else
                {
                    //初始情况下重新绑定
                    InitData();


                }
            }
        }

跳转到指定页面的代码如下:

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Jump")
            {
                try
                {
                    TextBox txt = (TextBox)GridView1.BottomPagerRow.FindControl("Pagenum");                  
                    int pagenum = int.Parse(txt.Text);

                    GridViewPageEventArgs ea = new GridViewPageEventArgs(pagenum - 1);
                    GridView1_PageIndexChanging(null, ea);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

(二)每行绑定特殊控件

有时候,我们要在列表中每一行中加入除TextBox以外的其他特殊控件,比如DropDownList控件,来修改分类等,这类特殊控件的内嵌,主要是在GridView1_RowDataBound()实现的

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //绑定上传人,根据用户ID查询用户名,然后绑定单独列
            if (((Label)e.Row.FindControl("lbl_Softupuserid")) != null && ((HiddenField)e.Row.FindControl("hf_Softupuserid")) != null)
            {
                Label lbl_Softupuserid = (Label)e.Row.FindControl("lbl_Softupuserid");
                HiddenField hf_Softupuserid = (HiddenField)e.Row.FindControl("hf_Softupuserid");
                // Users us = UserService.GetTheUsers(hf_Softupuserid.Value);

                lbl_Softupuserid.Text = "管理员";
            }

        

            //绑定DDL 所属类别
            if (((DropDownList)e.Row.FindControl("ddl_SoftClassname")) != null)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddl_SoftClassname");
                HiddenField hf = (HiddenField)e.Row.FindControl("hf_softclassname");

                foreach (ListItem item in ddl.Items)
                {
                    if (item.Text == hf.Value)
                    {
                        item.Selected = true;
                    }
                }
            }

            //绑定推荐
            if (((Label)e.Row.FindControl("lbl_recommand")) != null)
            {
                Label lbl_rec = (Label)e.Row.FindControl("lbl_recommand");

                if (lbl_rec.Text == "1")
                {
                    lbl_rec.Text = "首页显示";
                }
                else
                {
                    lbl_rec.Text = "未推荐";
                }
            }
            if (((DropDownList)e.Row.FindControl("ddlToTop")) != null)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddlToTop");
                //HiddenField hf = (HiddenField)e.Row.FindControl("hf_softclassname");
                HiddenField hf_rec = (HiddenField)e.Row.FindControl("hf_recommand");
                foreach (ListItem item in ddl.Items)
                {
                    if (item.Value == hf_rec.Value)
                    {
                        item.Selected = true;
                    }
                }
            }
        }

在这个方法里面,也可以绑定样式,例如奇偶行不同色等。

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#cbe2fa'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
        }
    }

(三)行、列样式

每一列数据居中等样式,主要通过控件的HeaderStyle-CssClass="headcenter" HeaderStyle-Width="100"  ItemStyle-HorizontalAlign="Center“属性来实现的。

(四)常见错误

1、有人在调试跳转到指定页代码时,总是无法获取到正确的Pagenum值。

解决方法:

      要在页面加载方法Page_Load中,加入如下代码:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
               .....
             }
        }

      如果,没有该代码Page.IsPostBack,则每次点击asp.net控件,页面都会认为是刷新,所有每次的Pagenum值都是初始值。

      在asp.net中,页面基础有个回传机制,postback就是回传,即页面在首次加载后向服务器提交数据,然后服务器把处理好的数据传递到客户端并显示出来,就叫postback; Ispostback只是一个属性,即判断页面是否是回传,if(!Ispostback)就表示页面是首次加载,这是很常用的一个判断方式.一个页面只能加载一次,但可以在加载后反复postback。

      每次页面Load的时候,根据需要把每次都要加载的代码放在IsPostBack中,只需要加载一次的代码放在if(!IsPostBack)中。

2、分析器错误消息: 未知的服务器标记“asp:ScriptManager”。 原因web.config,没有配置好!

解决方法:加入

 <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

原因:

      1, ScriptManager(脚本控制器)是asp.net ajax存在的基础.
      2, 一个页面只允许有一个ScriptManager,并且放在其他ajax控件的前面.
      3,ScriptManager掌管着客户端Ajax页的多有脚本,并在页面中注册Ajax类库,用来实现页面的局部更新和对Web服务的调用.
 

相关文章:

  • B+树索引(13)之索引挑选(下)
  • 每日leetcode[回文数】
  • 线性代数贯串全书各章节的隐含关系(以秩为中心)
  • ​二进制运算符:(与运算)、|(或运算)、~(取反运算)、^(异或运算)、位移运算符​
  • 算法--分隔链表(Kotlin)
  • Postgresql查询执行模块README笔记
  • 【二叉树】最大二叉树 II
  • java毕业设计小说网站mybatis+源码+调试部署+系统+数据库+lw
  • 【每日一题】 和为 K 的子数组
  • 【初认Redis】
  • HTTP之Hop-by-hop首部
  • 指标体系搭建-专项1
  • 尚好房 10_Spring Security
  • JDK RMI探索与使用--序列化
  • Self-supervised Low Light Image Enhancement and Denoising 论文阅读笔记
  • chrome扩展demo1-小时钟
  • ECMAScript入门(七)--Module语法
  • HTTP请求重发
  • Javascripit类型转换比较那点事儿,双等号(==)
  • k8s如何管理Pod
  • nodejs:开发并发布一个nodejs包
  • Promise面试题2实现异步串行执行
  • Spark学习笔记之相关记录
  • SpringCloud集成分布式事务LCN (一)
  • weex踩坑之旅第一弹 ~ 搭建具有入口文件的weex脚手架
  • 初探 Vue 生命周期和钩子函数
  • 高性能JavaScript阅读简记(三)
  • 技术攻略】php设计模式(一):简介及创建型模式
  • 前端代码风格自动化系列(二)之Commitlint
  • 跳前端坑前,先看看这个!!
  • 通过npm或yarn自动生成vue组件
  • 我的zsh配置, 2019最新方案
  • 译有关态射的一切
  • 【干货分享】dos命令大全
  • ionic入门之数据绑定显示-1
  • ​草莓熊python turtle绘图代码(玫瑰花版)附源代码
  • (07)Hive——窗口函数详解
  • (1)(1.19) TeraRanger One/EVO测距仪
  • (ZT) 理解系统底层的概念是多么重要(by趋势科技邹飞)
  • (八)Docker网络跨主机通讯vxlan和vlan
  • (板子)A* astar算法,AcWing第k短路+八数码 带注释
  • (初研) Sentence-embedding fine-tune notebook
  • (二)构建dubbo分布式平台-平台功能导图
  • (附源码)springboot工单管理系统 毕业设计 964158
  • (附源码)ssm航空客运订票系统 毕业设计 141612
  • (欧拉)openEuler系统添加网卡文件配置流程、(欧拉)openEuler系统手动配置ipv6地址流程、(欧拉)openEuler系统网络管理说明
  • (十) 初识 Docker file
  • (四)Tiki-taka算法(TTA)求解无人机三维路径规划研究(MATLAB)
  • (转)fock函数详解
  • (转载)虚幻引擎3--【UnrealScript教程】章节一:20.location和rotation
  • .htaccess配置重写url引擎
  • .Net FrameWork总结
  • .net 无限分类
  • .net实现头像缩放截取功能 -----转载自accp教程网
  • .NET中winform传递参数至Url并获得返回值或文件