Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

GridView Sort by Cell Text instead of SQL data

Posted on 2008-10-08
3
Medium Priority
?
655 Views
Last Modified: 2012-05-05
I have a gridview populated via a SqlDataSource.  It pulls data from a 'Companies' table, including columns such as 'OwnerID', 'CoordinatorID', 'ContactPersonID', etc.  

Since I want names displayed instead of IDs for these columns, I used template fields within the gridview to perform functions that lookup the names in other tables using the ID values and return them to the templates.  This creates a problem when trying to sort the gridview, since it's sorting with the data IDs instead of the names that I've manually inserted.  

I'd prefer to keep the SQL the same so that I don't have to maneuver a bunch of messy joins into my query.  

Any suggestions?
HTML:
 
            <asp:GridView ID="ReportGrid" runat="server" AutoGenerateColumns="False" DataKeyNames="CompanyID" OnSorting="GridView1_Sorting"
                AllowSorting="True" BorderColor="#E0E0E0" CellPadding="2" Font-Names="Arial" Font-Size="10pt" Font-Strikeout="False" DataSourceID="MyDataSource">
                <Columns>
                    <asp:BoundField DataField="CompanyID" HeaderText="CompanyID" InsertVisible="False"
                        ReadOnly="True" SortExpression="CompanyID" Visible="False" />
                    <asp:BoundField DataField="Name" HeaderText="Company Name" SortExpression="Name" />
                    <asp:BoundField DataField="CreatorID" HeaderText="CreatorID" SortExpression="CreatorID"
                        Visible="False" />
                    <asp:BoundField DataField="CreatedDate" HeaderText="CreatedDate" SortExpression="CreatedDate"
                        Visible="False" />
                    <asp:TemplateField HeaderText="OwnerID" SortExpression="OwnerID">
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# GetName(Eval("OwnerID").ToString()) %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="CoordinatorID" SortExpression="CoordinatorID">
                        <ItemTemplate>
                            <asp:Label ID="Label4" runat="server" Text='<%# GetName(Eval("CoordinatorID").ToString()) %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="LastModifiedID" SortExpression="LastModifiedID" Visible="False">
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# GetName(Eval("LastModifiedID").ToString()) %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="LastModifiedDate" HeaderText="LastModifiedDate" SortExpression="LastModifiedDate"
                        Visible="False" />
                    <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
                    <asp:TemplateField HeaderText="Contract Type" InsertVisible="False" SortExpression="CompanyID">
                        <ItemTemplate>
                            <asp:Label ID="Label5" runat="server" Text='<%# GetContractInfo(Eval("CompanyID").ToString(), "ContractType") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource ID="MyDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" SelectCommand="SELECT * FROM [Companies]"></asp:SqlDataSource>
 
 
Code Behind:
 
 
    Public Function GetName(ByVal ID As String) As String
 
        Dim Name As String = "Unknown"
 
        Dim conn As New SqlClient.SqlConnection(ConnectionString)
        Dim rdrQuery As String = "Select FirstName + LastName FROM Users WHERE UserID='" & ID & "'"
        conn.Open()
        Dim cmd As New SqlClient.SqlCommand(rdrQuery, conn)
        Dim rdr As SqlClient.SqlDataReader = cmd.ExecuteReader()
        Try
            While rdr.Read()
                Name = rdr.Item(0)
            End While
        Catch ex As Exception
        Finally
            conn.Close()
        End Try
 
        Return Name
 
    End Function
 
    Public Function GetContractInfo(ByVal CompanyID As String, ByVal Field As String) As String
 
        Dim Value As String = "Unknown"
 
        Dim conn As New SqlClient.SqlConnection(ConnectionString)
        Dim rdrQuery As String = "Select " & Field & " FROM Contracts WHERE CompanyID='" & CompanyID & "' And IsMain=1"
        conn.Open()
        Dim cmd As New SqlClient.SqlCommand(rdrQuery, conn)
        Dim rdr As SqlClient.SqlDataReader = cmd.ExecuteReader()
        Try
            While rdr.Read()
                Value = rdr.Item(0)
            End While
        Catch ex As Exception
        Finally
            conn.Close()
        End Try
 
        Try
            Value = Format(CDate(Value), "MM/dd/yyyy")
        Catch ex As Exception
        End Try
 
        Return Value
 
    End Function

Open in new window

0
Comment
Question by:askrenes
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 37

Expert Comment

by:samtran0331
ID: 22670000
>>I used template fields within the gridview to perform functions that lookup the names

With what you have, each row in the grid is going to make 4 separate database calls to get the name based on an id...
So if you have 20 rows, you're going to make 80 database calls ...

quite honestly, you're much much better off doing the joins in the sql
0
 

Author Comment

by:askrenes
ID: 22670043
That's a valid point.  Can you suggest a query (based on the info I have in the code)?  I'm not very good with joins.  
0
 
LVL 37

Accepted Solution

by:
samtran0331 earned 2000 total points
ID: 22671706
So it looks like all "users" regardless of being the Owner, Coordinator, or Last Modified...they are all in the "Users" table correct?

Run the below in query analyzer and see if the results are what you expect.

SELECT 
	Companies.*,
	Users.FirstName + Users.LastName AS OwnerName, 
	Users_1.FirstName + Users_1.LastName AS CoordinatorName, 
	Users_2.FirstName + Users_2.LastName AS LastModifiedName, 
	Contracts.ContractType
FROM         
	Companies LEFT OUTER JOIN
	Users AS Users_2 ON Companies.LastModifiedID = Users_2.UserID LEFT OUTER JOIN
	Contracts ON Companies.CompanyID = Contracts.CompanyID LEFT OUTER JOIN
	Users AS Users_1 ON Companies.CoordinatorID = Users_1.UserID LEFT OUTER JOIN
	Users ON Companies.OwnerID = Users.UserID
WHERE     
	(Contracts.IsMain = 1)

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

609 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question