Datagrid的一些应用(一)

一、DATAGRID普通翻页

DataGridPaging.aspx

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="DataGridPaging.aspx.vb" Inherits="DataGridPaging"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
  <HEAD>
    <meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
    <meta content="JavaScript" name="vs_defaultClientScript">
    <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
  </HEAD>
  <body MS_POSITIONING="GridLayout">
    <form id="Form1" runat="server">
      <asp:datagrid id="MyDataGrid" runat="server" AlternatingItemStyle-BackColor="#eeeeee"
    HeaderStyle-BackColor="#aaaadd" Font-Size="8pt" Font-Name="Verdana" CellSpacing="0"
     CellPadding="3" GridLines="Both" BorderWidth="1" BorderColor="black"
   OnPageIndexChanged="MyDataGrid_Page" PagerStyle-HorizontalAlign="Right"
    PagerStyle-Mode="NumericPages" PageSize="5" AllowPaging="True">
        <AlternatingItemStyle BackColor="#EEEEEE"></AlternatingItemStyle>
        <HeaderStyle BackColor="#AAAADD"></HeaderStyle>
        <PagerStyle HorizontalAlign="Right" Mode="NumericPages"></PagerStyle>
      </asp:datagrid>
      <p style="font-size:9pt">
        <asp:label id="lblPageCount" runat="server"></asp:label>&nbsp;
        <asp:label id="lblCurrentIndex" runat="server"></asp:label>
        <asp:linkbutton id="btnFirst" οnclick="PagerButtonClick" runat="server"
   Font-Name="verdana" Font-size="8pt" ForeColor="navy" CommandArgument="0">
   </asp:linkbutton>&nbsp;
        <asp:linkbutton id="btnPrev" οnclick="PagerButtonClick" runat="server"
   Font-Name="verdana" Font-size="8pt" ForeColor="navy" CommandArgument="prev">
   </asp:linkbutton>&nbsp;
        <asp:linkbutton id="btnNext" οnclick="PagerButtonClick" runat="server"
   Font-Name="verdana" Font-size="8pt" ForeColor="navy" CommandArgument="next">
   </asp:linkbutton>&nbsp;
        <asp:linkbutton id="btnLast" οnclick="PagerButtonClick" runat="server"
   Font-Name="verdana" Font-size="8pt" ForeColor="navy" CommandArgument="last">
   </asp:linkbutton>
      </p>
    </form>
  </body>
</HTML>

DataGridPaging.aspx.vb

Imports System.Data.SqlClient
Imports System.Data
Imports System.Web.UI

Public Class DataGridPaging
  Inherits System.Web.UI.Page

  Protected WithEvents MyDataGrid As System.Web.UI.WebControls.DataGrid
  Protected WithEvents btnFirst As System.Web.UI.WebControls.LinkButton
  Protected WithEvents btnPrev As System.Web.UI.WebControls.LinkButton
  Protected WithEvents btnNext As System.Web.UI.WebControls.LinkButton
  Protected WithEvents btnLast As System.Web.UI.WebControls.LinkButton
  Protected WithEvents lblCurrentIndex As System.Web.UI.WebControls.Label
  Protected WithEvents lblPageCount As System.Web.UI.WebControls.Label
  Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid

#Region " Web Form Designer Generated Code "

  'This call is required by the Web Form Designer.
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

  End Sub

  Private Sub Page_Init(ByVal sender As System.Object,_
   ByVal e As System.EventArgs) Handles MyBase.Init
    'CODEGEN: This method call is required by the Web Form Designer
    'Do not modify it using the code editor.
    InitializeComponent()
  End Sub

#End Region

  Private Sub Page_Load(ByVal sender As System.Object,_
   ByVal e As System.EventArgs) Handles MyBase.Load
    btnFirst.Text = "最首页"
    btnPrev.Text = "前一页"
    btnNext.Text = "下一页"
    btnLast.Text = "最后页"
    OpenDatabase()
    BindGrid()
  End Sub


  Sub MyDataGrid_Page(ByVal sender As Object, ByVal e As DataGridPageChangedEventArgs)
    Dim startIndex As Integer
    startIndex = MyDataGrid.CurrentPageIndex * MyDataGrid.PageSize
    MyDataGrid.CurrentPageIndex = e.NewPageIndex
    BindGrid()
    ShowStats()
  End Sub

  Sub BindGrid()
    Dim myConnection As SqlConnection = cn
    Dim ds As DataSet = New DataSet()
    Dim adapter As SqlDataAdapter = New SqlDataAdapter("Select * from Orders", myConnection)
    adapter.Fill(ds, "Orders")
    MyDataGrid.DataSource = ds.Tables("Orders").DefaultView
    MyDataGrid.DataBind()
    ShowStats()

  End Sub

  Sub PagerButtonClick(ByVal sender As Object, ByVal e As EventArgs)
    'used by external paging UI
    Dim arg As String = sender.CommandArgument

    Select Case arg
      Case "next"
        If (MyDataGrid.CurrentPageIndex < (MyDataGrid.PageCount - 1)) Then
          MyDataGrid.CurrentPageIndex += 1
        End If
      Case "prev"
        If (MyDataGrid.CurrentPageIndex > 0) Then
          MyDataGrid.CurrentPageIndex -= 1
        End If
      Case "last"
        MyDataGrid.CurrentPageIndex = (MyDataGrid.PageCount - 1)
      Case Else
        'page number
        MyDataGrid.CurrentPageIndex = System.Convert.ToInt32(arg)
    End Select
    BindGrid()
    ShowStats()
  End Sub

  Sub ShowStats()
    lblCurrentIndex.Text = "第 " + (MyDataGrid.CurrentPageIndex + 1).ToString() + " 页"
    lblPageCount.Text = "总共 " + MyDataGrid.PageCount.ToString() + " 页"
  End Sub

 Public cn As New SqlClient.SqlConnection()
  Public Sub OpenDatabase()
    cn.ConnectionString = "Server=.;Database=NorthWind;User Id=sa;Password=;"
    cn.Open()
  End Sub
End Class

 

二、DATAGRID带首页尾页
DataGridPaging.aspx

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="DataGridPaging.aspx.vb" Inherits="DataGridPaging"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
  <HEAD>
    <meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
    <meta content="JavaScript" name="vs_defaultClientScript">
    <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
  </HEAD>
  <body MS_POSITIONING="GridLayout">
    <form id="Form1" runat="server">
      <asp:datagrid id="MyDataGrid" runat="server" AlternatingItemStyle-BackColor="#eeeeee"
    HeaderStyle-BackColor="#aaaadd" Font-Size="8pt" Font-Name="Verdana" CellSpacing="0"
     CellPadding="3" GridLines="Both" BorderWidth="1" BorderColor="black"
   OnPageIndexChanged="MyDataGrid_Page" PagerStyle-HorizontalAlign="Right"
    PagerStyle-Mode="NumericPages" PageSize="5" AllowPaging="True">
        <AlternatingItemStyle BackColor="#EEEEEE"></AlternatingItemStyle>
        <HeaderStyle BackColor="#AAAADD"></HeaderStyle>
        <PagerStyle HorizontalAlign="Right" Mode="NumericPages"></PagerStyle>
      </asp:datagrid>
      <p style="font-size:9pt">
        <asp:label id="lblPageCount" runat="server"></asp:label>&nbsp;
        <asp:label id="lblCurrentIndex" runat="server"></asp:label>
        <asp:linkbutton id="btnFirst" οnclick="PagerButtonClick" runat="server"
   Font-Name="verdana" Font-size="8pt" ForeColor="navy" CommandArgument="0">
   </asp:linkbutton>&nbsp;
        <asp:linkbutton id="btnPrev" οnclick="PagerButtonClick" runat="server"
   Font-Name="verdana" Font-size="8pt" ForeColor="navy" CommandArgument="prev">
   </asp:linkbutton>&nbsp;
        <asp:linkbutton id="btnNext" οnclick="PagerButtonClick" runat="server"
   Font-Name="verdana" Font-size="8pt" ForeColor="navy" CommandArgument="next">
   </asp:linkbutton>&nbsp;
        <asp:linkbutton id="btnLast" οnclick="PagerButtonClick" runat="server"
   Font-Name="verdana" Font-size="8pt" ForeColor="navy" CommandArgument="last">
   </asp:linkbutton>
      </p>
    </form>
  </body>
</HTML>
DataGridPaging.aspx.vb

Imports System.Data.SqlClient
Imports System.Data
Imports System.Web.UI

Public Class DataGridPaging
  Inherits System.Web.UI.Page

  Protected WithEvents MyDataGrid As System.Web.UI.WebControls.DataGrid
  Protected WithEvents btnFirst As System.Web.UI.WebControls.LinkButton
  Protected WithEvents btnPrev As System.Web.UI.WebControls.LinkButton
  Protected WithEvents btnNext As System.Web.UI.WebControls.LinkButton
  Protected WithEvents btnLast As System.Web.UI.WebControls.LinkButton
  Protected WithEvents lblCurrentIndex As System.Web.UI.WebControls.Label
  Protected WithEvents lblPageCount As System.Web.UI.WebControls.Label
  Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid

#Region " Web Form Designer Generated Code "

  'This call is required by the Web Form Designer.
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

  End Sub

  Private Sub Page_Init(ByVal sender As System.Object,_
   ByVal e As System.EventArgs) Handles MyBase.Init
    'CODEGEN: This method call is required by the Web Form Designer
    'Do not modify it using the code editor.
    InitializeComponent()
  End Sub

#End Region

  Private Sub Page_Load(ByVal sender As System.Object,_
   ByVal e As System.EventArgs) Handles MyBase.Load
    btnFirst.Text = "最首页"
    btnPrev.Text = "前一页"
    btnNext.Text = "下一页"
    btnLast.Text = "最后页"
    OpenDatabase()
    BindGrid()
  End Sub


  Sub MyDataGrid_Page(ByVal sender As Object, ByVal e As DataGridPageChangedEventArgs)
    Dim startIndex As Integer
    startIndex = MyDataGrid.CurrentPageIndex * MyDataGrid.PageSize
    MyDataGrid.CurrentPageIndex = e.NewPageIndex
    BindGrid()
    ShowStats()
  End Sub

  Sub BindGrid()
    Dim myConnection As SqlConnection = cn
    Dim ds As DataSet = New DataSet()
    Dim adapter As SqlDataAdapter = New SqlDataAdapter("Select * from Orders", myConnection)
    adapter.Fill(ds, "Orders")
    MyDataGrid.DataSource = ds.Tables("Orders").DefaultView
    MyDataGrid.DataBind()
    ShowStats()

  End Sub

  Sub PagerButtonClick(ByVal sender As Object, ByVal e As EventArgs)
    'used by external paging UI
    Dim arg As String = sender.CommandArgument

    Select Case arg
      Case "next"
        If (MyDataGrid.CurrentPageIndex < (MyDataGrid.PageCount - 1)) Then
          MyDataGrid.CurrentPageIndex += 1
        End If
      Case "prev"
        If (MyDataGrid.CurrentPageIndex > 0) Then
          MyDataGrid.CurrentPageIndex -= 1
        End If
      Case "last"
        MyDataGrid.CurrentPageIndex = (MyDataGrid.PageCount - 1)
      Case Else
        'page number
        MyDataGrid.CurrentPageIndex = System.Convert.ToInt32(arg)
    End Select
    BindGrid()
    ShowStats()
  End Sub

  Sub ShowStats()
    lblCurrentIndex.Text = "第 " + (MyDataGrid.CurrentPageIndex + 1).ToString() + " 页"
    lblPageCount.Text = "总共 " + MyDataGrid.PageCount.ToString() + " 页"
  End Sub

 Public cn As New SqlClient.SqlConnection()
  Public Sub OpenDatabase()
    cn.ConnectionString = "Server=.;Database=NorthWind;User Id=sa;Password=;"
    cn.Open()
  End Sub
End Class
 

三、datagrid的更新,是否激发验证控件
  //datagrid的更新,是否激发DATAGRID里的验证控件


Private Sub lianjie_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles lianjie.ItemDataBound
If (e.Item.ItemType = ListItemType.EditItem) Then
            setUpdateCommandCausesValidation(e.Item, true)
        End If
    End Sub
Private Function setUpdateCommandCausesValidation(ByVal item As DataGridItem, ByVal valor As Boolean) As String

        If (item.HasControls()) Then

            For Each celula As Control In item.Controls

                For Each possibleButton As Control In celula.Controls

                    If (possibleButton.GetType().Name.Equals("DataGridLinkButton")) Then

                        Dim lbt As LinkButton = CType(possibleButton, LinkButton)

                        If (lbt.Text.Equals(getUpdateColumnText())) Then

                            lbt.CausesValidation = valor

                            Exit For

                        End If

                    End If

                Next

            Next

        End If

    End Function

    Private Function getUpdateColumnText() As String

        Dim text As String = ""

        For Each coluna As DataGridColumn In lianjie.Columns

            If (coluna.GetType().Name.Equals("EditCommandColumn")) Then

                Dim colunaEdit As EditCommandColumn = CType(coluna, EditCommandColumn)

                text = colunaEdit.UpdateText

                Exit For

            End If

        Next

        Return text

    End Function

 


  //datagrid的更新,是否激发DATAGRID外的验证控件

 Private Sub lianjie_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles lianjie.ItemDataBound

        If e.Item.ItemIndex >= 0 Then
            Dim btn As LinkButton = e.Item.Cells(5).Controls(0)
            btn.CausesValidation = False
        End If
    End Sub

四、DATAGRID的事件
Happy New Year!辛苦了一年,大家可以好好放松一下,尽管这个元旦只放一天假。谢谢CSDN的工作人员,辛辛苦苦地忙碌了一年,服务器扩容、网站改版……希望在明年CSDN再接再励,工作更出色,让网友们更开心。祝福大家心想事成,万事如意!

本文主要介绍.net Datagrid控件的事件响应,关于事件响应机制问题请参见拙作《Windows 窗体引介(二) 》。本文讨论的是Datagrid的鼠标响应与键盘响应问题:

一、鼠标响应

由于Datagrid的集合性结构(这在拙作Datagrid结构剖析系列文章中已经详细说明了),使得用户不清楚鼠标响应的响应区与处理者。请看图1:

                 图1  Datagrid响应区命名

1. 单击事件

如果用户要单击datagrid来激发某相应事件,可以使用Datagrid.HitTest方法来获得单击在Datagrid上的位置,必由系统通知您单击在何处。如下代码:

   Private Sub DataGrid1_MouseDown(ByVal sender As Object, ByVal e As _

System.Windows.Forms.MouseEventArgs) Handles DataGrid1.MouseDown

        Dim myGrid As DataGrid = CType(sender, DataGrid)

        Dim hti As System.Windows.Forms.DataGrid.HitTestInfo

        hti = myGrid.HitTest(e.X, e.Y)

        Select Case hti.Type  '以下展示的是该类型枚举的全部内容

            Case System.Windows.Forms.DataGrid.HitTestType.None

                MsgBox("你单击的是背景")

            Case System.Windows.Forms.DataGrid.HitTestType.Cell

                MsgBox("你单击的单元格位于行:" & hti.Row & ",  列:" & hti.Column)

            Case System.Windows.Forms.DataGrid.HitTestType.ColumnHeader

                MsgBox("你单击的是第" & hti.Column & "列的列头")

            Case System.Windows.Forms.DataGrid.HitTestType.RowHeader

                MsgBox("你单击的是第" & hti.Row & "行的行头")

            Case System.Windows.Forms.DataGrid.HitTestType.ColumnResize

                MsgBox("你单击的是第" & hti.Column & "列的边框")

            Case System.Windows.Forms.DataGrid.HitTestType.RowResize

                MsgBox("你单击的是第" & hti.Row & "行的边框")

            Case System.Windows.Forms.DataGrid.HitTestType.Caption

                MsgBox("你单击的是标题 ")

            Case System.Windows.Forms.DataGrid.HitTestType.ParentRows

                MsgBox("你单击的是父行 ")

        End Select

 End Sub

2. 双击事件(感谢acptvb网友的帮助)

在上面的单击事件中稍加修改,就可得到双击事件,只需要在sub里加入如下的判断语句:

    If e.Button = MouseButtons.Left And e.Clicks = 2 Then

Dim myGrid As DataGrid = CType(sender, DataGrid)

    …

End Select

End If

您再试一下运行,却发现其它一切正常,只有单元格双击事件获得不到,这是什么原因呢?道理很简单,就是在您第一次单击cell时,datagrid还可以获得消息,但是单击的结果是使焦点落入了您单击的那个cell中去了,您的第二次鼠标点击事件的响应者就不再是datagrid,而是cell中的textbox了。(如果不是很理解这个,请看一下我专栏中的datagrid结构剖析文章)。那么怎么样通知datagrid还有一次本属于双击cell事件的第二次点击呢?首先我们应该明晰何谓两次单击与双击,它们的区别就在于鼠标点击两下之间的时间间隔,间隔短的就是双击事件,达到一定长度后就被视为是两次单击(时间间隔的设定其实是可以人工完成的,在您机器的“控制面板”中有“鼠标”一项,里面就有调整这个时间间隔的工具)。这个时间设定完毕后,可以通过SystemInformation.DoubleClickTime方法去获得。

现在我们来理一下思路:

(1)     设置一个公用变量gridMouseDownTime,用于记录点击时的绝对时间;

(2)       在DataGrid1_MouseDown事件处理程序中记录下第一次点击的时间:

If hit.type= System.Windows.Forms.DataGrid.HitTestType.Cell then

   gridMouseDownTime = DateTime.Now

End If

(3)       在Datagrid的cell内嵌的textbox中设置鼠标点击事件(mousedown);

设置方法请看我专栏中的datagrid结构剖析文章,事件处理程序的设置方法请看我专栏中的windows窗体引介(二)中的事件响应部分,在此不重复解释了:

Dim ts As New DataGridTableStyle() 

        Dim aColumnTextColumn As DataGridTextBoxColumn

        DataGrid1.DataSource = dt

        Me.HenryDatagrid1.DataSource = dt

        ts.MappingName = dt.TableName

        Dim numCols As Integer

        numCols = dt.Columns.Count

Do While (i < numCols) '重绘所有的列

            aColumnTextColumn = New DataGridTextBoxColumn()

            '夺过对textbox内落下光标的控制权,但你仍可以输入值

AddHandler aColumnTextColumn.TextBox.MouseDown, New MouseEventHandler _
(AddressOf TextBoxMouseDownHandler)
            aColumnTextColumn.HeaderText = dt.Columns(i).ColumnName            aColumnTextColumn.MappingName = dt.Columns(i).ColumnName
            ts.GridColumnStyles.Add(aColumnTextColumn)  '增加一种自定义的column风格
            i = (i + 1)
         Loop
DataGrid1.TableStyles.Add(ts)

(4)       在上述事件的事件处理程序中比较时间间隔,从而判断是否是datagrid中对某一个cell进行了双击:      Private Sub TextBoxMouseDownHandler(ByVal sender As Object, ByVal e As MouseEventArgs)
             If (DateTime.Now < gridMouseDownTime.AddMilliseconds(SystemInformation.DoubleClickTime)) Then ‘判断时间间隔
                MsgBox("DataGrid 的 DoubleClick  ")
            End If
        End If
End Sub

在这里需要读者注意的是,你点击的cell当然应该是没有被聚焦的(就是没有变蓝的),如果已经变蓝,再双击它就看不到弹出的"DataGrid 的 DoubleClick"对话框了,因为此时你的两次点击都是落在textbox里了,成为了textbox的双击事件,你可以在TextBoxMouseDownHandler中加入如下代码来进行观察:
If e.Button = MouseButtons.Left And e.Clicks = 2 Then
            MessageBox.Show("在单元格的textbox中的双击  ")
        Else
            If (DateTime.Now < gridMouseDownTime.AddMilliseconds(SystemInformation.DoubleClickTime)) Then
                MessageBox.Show("DataGrid 的 DoubleClick  ")
             End If
     End If
您可以完善上述的代码,以实现您的鼠标事件响应的需要。
键盘事件响应看来得明年再讨论了,我得去买菜了,不然女朋友回来要发飙了。再次祝福大家新年好!

 

五、DATAGRID排序
SortExpression="newsname"

  Private Sub news_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles news.SortCommand
        '得到排序的列

        If ViewState("strSort") = "asc" Then
            ViewState("strSort") = "desc"
            sql = "select newsid,newsname,addname,adddate from news order by " & e.SortExpression.ToString() & " " & ViewState("strSort").ToString
        Else
            ViewState("strSort") = "asc"
            sql = "select newsid,newsname,addname,adddate from news order by " & e.SortExpression.ToString() & " " & ViewState("strSort").ToString
        End If
        news.DataSource = getdataview(sql, "news")
        news.DataBind()
End Sub

 六、DATAGRID批量修改
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click

        '初始化连接字符串
        Dim CN As New SqlConnection()
        CN.ConnectionString = "data source=.;initial catalog=kingseer_db;persist security info=False;user id=kingseer_area;Password=kingseer_area;"
        CN.Open()
        Dim myCommand As New SqlCommand
        Dim dgi As DataGridItem
        For Each dgi In dgOrder.Items
            Dim id As Integer = Convert.ToInt32(dgOrder.FindControl("id"))
            Dim m_feename As String = CType(dgi.FindControl("m_feename"), TextBox).Text

            Dim updateSQL As String = "UPDATE t_meterdata SET m_feename = @m_feename  WHERE id = @ID"
            myCommand.Parameters.Clear()
            myCommand.Parameters.Add("@m_feename", m_feename)

            myCommand.ExecuteNonQuery()
        Next

    End Sub

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值