1

我在解决 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

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

4

1 回答 1

2

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

onsorting="gvUserSearch_Sorting"

这代表了一个事件处理程序,用于每当需要排序操作时,例如用户单击列的标题对其进行排序。

我建议您将您的DataSource类型更改为DataTable,因为DataTable数据结构有助于构建一个针对它的视图,稍后您将看到我们如何轻松地应用列的排序方向和排序表达式。这是一个实用函数,可以返回 aDataTable供您的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()

现在我们将源作为 a 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排序方向是什么,然后DataView从中创建一个DataTable并应用在网格视图列中定义的排序表达式,以及将数据源重新绑定到网格的排序方向。

于 2013-08-14T17:36:08.787 回答