VB Gridview 填充和排序

Posted

技术标签:

【中文标题】VB Gridview 填充和排序【英文标题】:VB Gridview Populating and Sorting 【发布时间】:2013-08-16 17:54:03 【问题描述】:

我在解决 GridView 的数据源时遇到问题。我尝试了多种编码变体,每种变体都有自己的问题。我使用 GridView 配置管理器定义了 DataSourceID。当我尝试调用我的存储过程来填充我的 GridView 时,我没有得到任何结果。因此,我尝试在代码隐藏中定义一个 DataSource 并手动绑定(并设置 DataSourceID = '' 以避免错误)。这很好地填充了我的 GridView,但不允许排序。

这是我的问题:有没有人看到我做错了什么,所以这些解决方案都不起作用?我从另一个项目中重新使用了代码,它们是相同的(在其他项目中,DataSourceID 和 Datasource 都使用没有错误?)这是我的 ASP.net Gridview 和 Proc 代码:

    <asp:GridView ID="gvUserSearch" runat="server" style="z-index: 1; left: 56px; top: 382px; position: absolute; height: 133px; width: 187px" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="UserSearchDataSource" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical">
<AlternatingRowStyle BackColor="Gainsboro" />
<Columns>
    <asp:CommandField ShowSelectButton="True" >
    <ItemStyle ForeColor="#0066FF" />
    </asp:CommandField>
    <asp:BoundField DataField="SubscriberID" HeaderText="SubscriberID" SortExpression="SubscriberID" Visible="False" />
    <asp:BoundField DataField="Last Name" HeaderText="Last Name" SortExpression="Last Name" >
    <HeaderStyle HorizontalAlign="Center" Wrap="False" />
    <ItemStyle HorizontalAlign="Left" Wrap="False" />
    </asp:BoundField>
    <asp:BoundField DataField="First Name" HeaderText="First Name" SortExpression="First Name" >
    <HeaderStyle HorizontalAlign="Center" Wrap="False" />
    <ItemStyle HorizontalAlign="Left" Wrap="False" />
    </asp:BoundField>
    <asp:BoundField DataField="EmailAddress" HeaderText="Email Address" SortExpression="EmailAddress" >
    <HeaderStyle HorizontalAlign="Center" Wrap="False" />
    <ItemStyle HorizontalAlign="Left" Wrap="False" />
    </asp:BoundField>
    <asp:BoundField DataField="locationid" HeaderText="Unit ID" SortExpression="locationid" >
    <HeaderStyle HorizontalAlign="Center" Wrap="False" />
    <ItemStyle HorizontalAlign="Center" Wrap="False" />
    </asp:BoundField>
    <asp:BoundField DataField="unit_name" HeaderText="Unit Name" SortExpression="unit_name" >
    <HeaderStyle HorizontalAlign="Center" Wrap="False" />
    <ItemStyle HorizontalAlign="Left" Wrap="False" />
    </asp:BoundField>
    <asp:BoundField DataField="Birthday" HeaderText="Birthday" ReadOnly="True" SortExpression="Birthday" DataFormatString="0:MMMM/DD/yyyy" htmlEncode="False" HtmlEncodeFormatString="False" >
    <ItemStyle HorizontalAlign="Center" Wrap="False" />
    </asp:BoundField>
    <asp:BoundField DataField="Zip Code" HeaderText="Zip Code" SortExpression="Zip Code" >
    <HeaderStyle HorizontalAlign="Center" Wrap="False" />
    <ItemStyle HorizontalAlign="Center" Wrap="False" />
    </asp:BoundField>
    <asp:BoundField DataField="Status" HeaderText="Status" ReadOnly="True" SortExpression="Status" >
    <HeaderStyle HorizontalAlign="Center" Wrap="False" />
    <ItemStyle HorizontalAlign="Left" Wrap="False" />
    </asp:BoundField>
    <asp:BoundField DataField="DateUnsubscribed" HeaderText="Unsubscribe Date" ReadOnly="True" SortExpression="DateUnsubscribed" DataFormatString="0:MMMM/DD/yyyy" HtmlEncode="False" >
    <HeaderStyle HorizontalAlign="Center" Wrap="False" />
    <ItemStyle HorizontalAlign="Center" Wrap="False" />
    </asp:BoundField>
</Columns>

<asp:SqlDataSource ID="UserSearchDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:CafeWorksConnectionString %>" SelectCommand="MarketingPortal_UserSearchProc" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="txtEmail" Name="Email" PropertyName="Text" Type="String" />
            <asp:ControlParameter ControlID="txtLastName" Name="LastName" PropertyName="Text" Type="String" />
            <asp:ControlParameter ControlID="txtFirstName" Name="FirstName" PropertyName="Text" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>

这是我的 VB.net 代码隐藏:

Dim CafeWorksConnection As New SqlConnection()
Dim CafeWorksCS As String
Dim CafeWorksDA As SqlDataAdapter
Dim CafeWorksCB As SqlCommandBuilder
Dim CafeWorksDS As New DataSet
Dim CafeWorksSqlC As New SqlCommand
Dim CafeWorksReader As SqlDataReader

 Private Sub DBConnect()
    'Get the connection string from the web.config file
    CafeWorksCS = ConfigurationManager.ConnectionStrings("CafeWorksConnectionString").ConnectionString

    'Assign the Connection String to the Connection
    CafeWorksConnection.ConnectionString = CafeWorksCS

    'Open the database connection
    CafeWorksConnection.Open()
End Sub

Private Sub Populate_GridView()
    'Make a database connection
    DBConnect()

    'Define the type of query being executed (Stored Procedure)
    CafeWorksSqlC.CommandType = CommandType.StoredProcedure
    CafeWorksSqlC.CommandText = "MarketingPortal_UserSearchProc "

    'Define the stored procedure parameters
    CafeWorksSqlC.Parameters.AddWithValue("@Email", txtEmail.Text)
    CafeWorksSqlC.Parameters.AddWithValue("@LastName", txtLastName.Text)
    CafeWorksSqlC.Parameters.AddWithValue("@FirstName", txtFirstName.Text)

    'Make a connection for the stored procedure to run
    CafeWorksSqlC.Connection = CafeWorksConnection
    'CafeWorksConnection.Open()

    'Executes the stored procedure and stores the result set
    CafeWorksReader = CafeWorksSqlC.ExecuteReader()

    'You need to bind the data to the GridView
    'Got error that DataSourceID and DataSource can't be defined (DataSourceID define in Gridview ASP.net
    'code and is not giving me a result set for some reason, so I added the DataSource and DataBind
    'gvUserSearch.DataSourceID = ""
    gvUserSearch.DataSource = CafeWorksDS
    gvUserSearch.DataBind()

    'Always close the database connection when you are finished
    CafeWorksConnection.Close()
End Sub

Protected Sub btnNameSearch_Click(sender As Object, e As EventArgs) Handles btnNameSearch.Click
    'Call the Sub Populate_GridView to display results of search
    Populate_GridView()

    'Clear out the text boxes - Keeps data from lingering into other searches
    txtEmail.Text = ""
    txtLastName.Text = ""
    txtFirstName.Text = ""
End Sub

我对此还比较陌生,而且我的代码可能并不漂亮。我将不胜感激任何人可以给我的任何帮助。谢谢!

【问题讨论】:

你的ColumnsGridView中定义在哪里? 抱歉,将我的专栏的 ASP.net 代码添加到原始问题中。 【参考方案1】:

您的第一个问题是您没有定义GridViewonsorting 属性,如下所示:

onsorting="gvUserSearch_Sorting"

这表示需要排序操作时的事件处理程序,例如用户单击列的标题对其进行排序。

我建议您将DataSource 类型更改为DataTable,因为DataTable 数据结构有助于构建一个针对它的视图,稍后您将看到我们如何轻松应用排序方向和列的排序表达式。这是一个实用函数,它可以返回 DataTable 以供您的 DataSource 属性使用:

Private Function GetGridViewDataSource() As DataTable
    Dim dtGrid As New DataTable()

    Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)

    ' Change this to either execute the SQL you want or change the command object to execute a stored procedure
    Dim strSelect As String = "SELECT FirstName,LastName,Location FROM Details"

    Dim cmd As New SqlCommand(strSelect, con)

    Dim dAdapter As New SqlDataAdapter(cmd)

    dAdapter.Fill(dtGrid)

    Return dtGrid
End Function

注意:您需要更改 DataSource 分配才能调用此函数,如下所示:gvUserSearch.DataSource = GetGridViewDataSource()

现在我们有了DataTable 的来源,我们可以开始管理排序,特别是通过类属性跟踪排序方向(升序或降序),如下所示:

Public Property dir() As SortDirection
    Get
        If ViewState("dirState") Is Nothing Then
            ViewState("dirState") = SortDirection.Ascending
        End If

        Return DirectCast(ViewState("dirState"), SortDirection)
    End Get

    Set
        ViewState("dirState") = value
    End Set
End Property

现在我们终于准备好实现实际的排序处理程序了,如下所示:

Protected Sub gvDetails_Sorting(sender As Object, e As GridViewSortEventArgs)
    Dim sortingDirection As String = String.Empty

    If dir = SortDirection.Ascending Then
        dir = SortDirection.Descending
        sortingDirection = "Desc"
    Else
        dir = SortDirection.Ascending
        sortingDirection = "Asc"
    End If

    Dim sortedView As New DataView(GetGridViewDataSource())
    sortedView.Sort = Convert.ToString(e.SortExpression) & " " & sortingDirection

    gvDetails.DataSource = sortedView
    gvDetails.DataBind()
End Sub

注意:此方法的作用是询问ViewState 的排序方向是什么,然后从DataTable 创建一个DataView 并应用网格视图列中定义的排序表达式和排序方向将数据源重新绑定到网格。

【讨论】:

谢谢卡尔。我现在正在尝试解决您的答案。在上面的 gvDetails_Sorting sub 中,出现了 - Dim sortedView As New DataView(BindGridView()) 行。我没有在任何地方定义。你能帮我理解我错过了什么吗? 很好,这是我在其他地方开发的示例代码的复制和粘贴错字。答案已更新。 我终于把我的“新”代码弄到了不产生错误的地步。我现在的问题是当我选择要排序的列时,整个 GridView 消失了。你知道这可能是什么原因吗? 你是在Page_Load中绑定网格还是没有? 没有。我在 Page_Load 中的唯一代码是将焦点设置到文本框。我所有的 GridView 填充都是在 GridView 配置或我的子 Populate_GridView 中完成的

以上是关于VB Gridview 填充和排序的主要内容,如果未能解决你的问题,请参考以下文章

VB.Net根据下拉文本选择隐藏特定的gridview列

使用VB在ASP.Net中对GridView中的事件进行排序

使用vb在asp.net中没有gridview的分页

在 vb.net 中的网站的 gridview 中显示表格

vb.net动态设置gridview列的属性

PySide2/QML 填充和动画 Gridview 模型/委托