1

GridView の DataSource の処理に問題があります。私はコーディングで複数のバリエーションを試しましたが、それぞれに独自の問題があります。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データ構造は、それに対してビューを構築するのに適しているためです。これについては、列の並べ替え方向と並べ替え式を簡単に適用する方法について後で説明します。プロパティ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、並べ替え方向が何であるかを に問い合わせてDataViewからを作成DataTableし、グリッド ビュー列で定義された並べ替え式と並べ替え方向を適用して、データ ソースをグリッドに再バインドすることです。

于 2013-08-14T17:36:08.787 に答える