ASP.NET:优化DataGrid控件的编辑功能

本文介绍如何使用DataGrid控件实现批量更新功能,通过实例展示如何优化编辑属性并减少服务器负担。涉及技术包括FindControl方法及数据库操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

尽管在上面的实例中我们已经实现了DataGrid的在线编辑功能,但是,如果我们已经习惯了C/S 结构的程序,就会感觉到上个实例中编辑的不足:提交数据频繁,加重了服务器的负担。在这一节中,我们利用一个实例来演示优化后的DataGrid控件的编辑功能,其中的技术就是引入批量更新数据。引入的一个新知识就是控件的FindControl方法。

    我们来看具体实例。首先在DataCon Web项目里,添加一个Web Form,命名为DataGrid_Sample6.aspx,然后添加一个DataGrid控件,由于我们做了DataGrid控件的显示模版,并且为了优化其编辑属性,我们特别利用<asp:TemplateColumn ><ItemTemplate></ItemTemplate></asp:TemplateColumn >属性添加了DropDownList控件和CheckBox控件。为了便于实例应用和读者理解,我们新建一个TeacherInfor.mdb数据库,该数据库包含一个teacher数据表 ,字段类型和虚拟数据如图9.11和9.12所示。

ASP.NET:优化DataGrid控件的编辑功能
图9.11 teacher数据表中的字段属性

ASP.NET:优化DataGrid控件的编辑功能
图9.12  teacher数据表中数据记录

DataGrid_Sample6.aspx的主要HTML代码如下:
<body topMargin="0" MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<FONT face="宋体"><b>经济管理学院教师信息</b>
   <asp:DataGrid id="DataGrid1"
      runat="server" AutoGenerateColumns="False" Width="320px" PageSize="4"
 AllowPaging="True">
 <AlternatingItemStyle BackColor="WhiteSmoke"></AlternatingItemStyle>
 <ItemStyle BackColor="GhostWhite"></ItemStyle>
  <HeaderStyle BackColor="LightSteelBlue"></HeaderStyle>
  <Columns>
   <asp:BoundColumn DataField="id" HeaderText="编号"></asp:BoundColumn>
   <asp:BoundColumn DataField="name" HeaderText="姓名"></asp:BoundColumn>
  <asp:TemplateColumn HeaderText="性别">
   <ItemTemplate>
    <asp:DropDownList id="sex" runat="server" SelectedIndex='<%# Cint(DataBinder.Eval(Container,"DataItem.sex")) %>' >
       <asp:ListItem Value="0">男</asp:ListItem>
     <asp:ListItem Value="1">女</asp:ListItem>
    </asp:DropDownList>
    </ItemTemplate>
  </asp:TemplateColumn>
  <asp:TemplateColumn HeaderText="所获学位">
   <ItemTemplate>
    <asp:DropDownList id="degree" runat="server" SelectedIndex='<%# cint(DataBinder.Eval(Container,"DataItem.degree")) %>'>
     <asp:ListItem Value="0">学士</asp:ListItem>
     <asp:ListItem Value="1">硕士</asp:ListItem>
     <asp:ListItem Value="2">博士</asp:ListItem>
     </asp:DropDownList>
    </ItemTemplate>
 </asp:TemplateColumn>
 <asp:TemplateColumn HeaderText="性别">
   <ItemTemplate>
    <asp:DropDownList id="title" runat="server" SelectedIndex='<%# Cint(DataBinder.Eval(Container,"DataItem.title")) %>' >
     <asp:ListItem Value="0">讲师</asp:ListItem>
     <asp:ListItem Value="1">副教授</asp:ListItem>
     <asp:ListItem Value="2">教授</asp:ListItem>
     </asp:DropDownList>
   </ItemTemplate>
 </asp:TemplateColumn>
  <asp:TemplateColumn HeaderText="婚否">
   <ItemTemplate>
    <asp:CheckBox Runat=server Checked ='<%# DataBinder.Eval(Container,"DataItem.marry") %>' ID="marry" Text ="婚否">
    </asp:CheckBox>
    </ItemTemplate>
    </asp:TemplateColumn>
 </Columns>
 <PagerStyle BackColor="LightSteelBlue" Mode="NumericPages"></PagerStyle>
 </asp:DataGrid> 
        <asp:button id="Button1" 
       runat="server" Text="批量更新">
         </asp:button></FONT>
</form>
</body>

在上面HTML代码中,注意DataGrid控件值的数据绑定:

SelectedIndex='<%# cint(DataBinder.Eval(Container,"DataItem.degree")) %>'
DataGrid_Sample6.aspx.vb中的逻辑代码如下:
'----code begin ----------
'-省略命名空间的引用
Public Class DataGrid_Sample6
    Inherits System.Web.UI.Page
#Region " Web 窗体设计器生成的代码 "
'此处省略窗体设计器生成的代码
 #End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '在此处放置初始化页的用户代码
        If Not IsPostBack Then
            getdata()
        End If
End Sub
    '读取数据
    Sub getdata()
        Dim mycon As OleDb.OleDbConnection
        viewstate("constr") = "provider=microsoft.jet.oledb.4.0;data source=" + Server.MapPath(".") + "/TeacherInfor.mdb"
        '使用viewsate保存Connection连接字符串
        Dim mycmd As OleDb.OleDbDataAdapter
        '声明DataAdapter对象
        Dim mysql As String
        '声明Command命令的 SQL字符串
        Try
            mycon = New OleDb.OleDbConnection(viewstate("constr"))
            '实例化Connection对象
            mysql = "Select id,name, sex ,degree, title,marry  from teacher"
            '设置SQL语句,即查询数据库中所有内容
            mycmd = New OleDb.OleDbDataAdapter(mysql, mycon)
            Dim dt As Data.DataSet = New Data.DataSet
            '声明DataSet对象,并实例话
            mycmd.Fill(dt)
            '填充数据,即在内存中生成DataSet模型数据库
            DataGrid1.DataSource = dt.Tables(0)
            '为DataGrid1控件指定数据源
            DataGrid1.DataBind()
            '执行绑定
        Catch ex As Exception
            Response.Write("程序出错,信息描述如下:<br>" & ex.Message)
        Finally
            mycon.Close()
        End Try
End Sub
    '翻页事件
Private Sub DataGrid1_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles DataGrid1.PageIndexChanged
        DataGrid1.CurrentPageIndex = e.NewPageIndex
        getdata()
End Sub
    '批量更新过程
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim mysql As String
        Dim sex As DropDownList
        Dim degree As DropDownList
        Dim title As DropDownList
        Dim marry As CheckBox
        Dim mycon As OleDb.OleDbConnection = New OleDb.OleDbConnection(viewstate("constr"))
        mycon.Open()
        Dim mycmd As OleDb.OleDbCommand
        Try
            Dim item As DataGridItem
            '定义item变量,代表这DataGrid控件的每一个Item项
            For Each item In DataGrid1.Items
                '遍历DataGrid1的Item项
                sex = item.FindControl("sex")
                '利用FindControl方法实例化性别字段的列表控件
                degree = item.FindControl("degree")
                '利用FindControl方法实例化学位字段的列表控件
                title = item.FindControl("title")
                '利用FindControl方法实例化职称字段的列表控件
                marry = item.FindControl("marry")
                '利用FindControl方法实例化婚否字段的列表控件
                '下面为mysql语句赋值,利用已经实例化的控件,就可以获取它的值。
                mysql = "update teacher set sex='" & sex.SelectedValue & "',degree='" & degree.SelectedValue & "'," & _
                     "marry=" & marry.Checked & ",title='" & title.SelectedValue & "'  where id=" & item.Cells(0).Text
                mycmd = New OleDb.OleDbCommand(mysql, mycon)
                '写入更新
                mycmd.ExecuteNonQuery()
            Next
        Catch ex As Exception
            Response.Write("程序出错,信息描述如下:<br>" & ex.Message)
        Finally
            mycon.Close()
            Response.Write("<script>alert('恭喜您!/n你已经成功的更新了记录!');</script>")
            '提示更新成功!
        End Try
        getdata()
End Sub
End Class
'------code end ---------

  保存编译后,DataGrid_Sample6.aspx运行效果如图9.13所示。

ASP.NET:优化DataGrid控件的编辑功能
如图9.13 DataGrid_Sample6.aspx运行效果

    通过以上几节的学习,我们对DataGrid控件已经有个比较详细的认识了。但我们知道,DataGrid控件是个功能十分强大的数据绑定控件,限于篇幅,只能粗略介绍,尚有很多功能只有在实际应用中,多探索,多实践,才能真正掌握。在下面一节里,我们将一起来学习另一个数据绑定控件――DataList控件。
分页是Web应用程序中最常用到的功能之一,在ASP.NET中,虽然自带了一个可以分页的DataGridasp.net 1.1)和GridView(asp.net 2.0)控件,但其分页功能并不尽如人意,如可定制性差、无法通过Url实现分页功能等,而且有时候我们需要对DataList和Repeater甚至自定义数据绑定控件进行分页,手工编写分页代码不但技术难度大、任务繁琐而且代码重用率极低,因此分页已成为许多ASP.NET程序员最头疼的问题之一。 AspNetPager针对ASP.NET分页控件的不足,提出了与众不同的解决asp.net中分页问题的方案,即将分页导航功能与数据显示功能完全独立开来,由用户自己控制数据的获取及显示方式,因此可以被灵活地应用于任何需要实现分页导航功能的地方,如为GridView、DataList以及Repeater等数据绑定控件实现分页、呈现自定义的分页数据以及制作图片浏览程序等,因为AspNetPager控件和数据是独立的,因此要分页的数据可以来自任何数据源,如SQL Server、Oracle、Access、mysql、DB2等数据库以及XML文件、内存数据或缓存中的数据、文件系统等等。 AspNetPager 7.2 版发布 新增属性 PagingButtonLayoutType,可设置分页导航元素(数字页索引、上页、下页、首页和尾页)的布局方式,该属性值是一个PagingButtonLayoutType枚举,通过设置该属性为PagingButtonLayoutType.UnorderedList或PagingButtonLayoutType.Span,允许将这些分页导航元素包含在 与或与标签之间,以便于为这些分页元素应用CSS样式。 新增 PagingButtonClass 与 PagingButtonStyle 属性,可以单独为分页导航按钮(数字页索引、上页、下页、首页和尾页)设置CSS样式; 新增 FirstLastButtonClass 与 FirstLastButtonStyle 属性,可以单独为首页和尾页分页导航按钮设置CSS样式,如果该属性未设置,但指定了PagingButtonClass 与 PagingButtonStyle 属性的值,则首页和尾页按钮样式将使用 PagingButtonClass 与 PagingButtonStyle 属性中指定的样式; 新增 NextPrevButtonClass 与 NextPrevButtonStyle 属性,可以单独为上页和下页分页导航按钮设置CSS样式,如果该属性未设置,但指定了PagingButtonClass 与 PagingButtonStyle 属性的值,则上页和下页按钮样式将使用 PagingButtonClass 与 PagingButtonStyle 属性中指定的样式; 新增 MoreButtonClass 与 MoreButtonStyle 属性,可以单独为更多页(...)分页导航按钮设置CSS样式,如果该属性未设置,但指定了PagingButtonClass 与 PagingButtonStyle 属性的值,则上页和下页按钮样式将使用 PagingButtonClass 与 PagingButtonStyle 属性中指定的样式; 新增属性 ShowMoreButtons ,可以指定是否显示更多页按钮; 新增属性 CurrentPageButtonPosition ,可设置在每次分页后,当前页数字索引在所有的数字页索引中的显示位置,该属性值是一个PagingButtonPosition枚举,对应的值及说明如下: Beginning:当前页数字索引总是显示在所有数字页索引的最前面; End:当前页数字索引总是显示在所有数字页索引的最后面; Center:当前页数字索引总是显示在所有数字页索引的中间; Fixed:默认值,固定不变; 控件的CssClass属性仅应用于控件的窗口元素(div),将不再应用于下属分页元素; 废止属性CenterCurrentPageButton,可以用CurrentPageButtonPosition属性取代; 修改CurrentPageIndexn属性,允许在程序中任何地方以编程方式设置CurrentPageIndex的值来动态指定当前页,直接设置该属性的值时将同时引发PageChanging和PageChanged 事件,实现和点击分页按钮一样的分页功能; 修正了7.1版中设置SubmitButtonImageUrl属性后,Postback回发分页方式情况下点击数字页索引按钮不引发分页事件的bug; 修正了使用Url分页时,如果页面上没有服务器端form控件时无法注册客户端脚本的bu
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值