Solved

Gridview - Matrix format

Posted on 2011-03-03
3
1,303 Views
Last Modified: 2012-08-14
I want to display the data in the following format in a gridview whenever a user is selected.

              Username1     Username2     Password
IPAD         XXXXX11        XXXXX21         XXXXXp1
PC1          XXXXX12        XXXXX22         XXXXXp2
PC2          XXXXX13        XXXXX23         XXXXXp3    
PC3          XXXXX14        XXXXX24         XXXXXp4  

I have two tables 1) tblMachines 2)tblPasswords
1) tblMachine -->
     MachineId,
     MachineName
2) tblPasswords -->
     PassId
     UserId
     MachineId
     Username1
     Username2
     Password

Would someone help me. Thanks.
0
Comment
Question by:cimscims
  • 2
3 Comments
 
LVL 96

Expert Comment

by:Bob Learned
Comment Utility
That looks like a pivot/cross-tab, but you didn't indicate the database that you are using.  That could either be the job for a query, or you could do it in code also.
0
 

Author Comment

by:cimscims
Comment Utility
I am using SQL Server 2000. Would you please help me out. Thanks.
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
Comment Utility
SQL Server 2000 does not support the PIVOT and UNPIVOT keywords, since they were added in 2005.  That would mean that you need to do the cross-tab pivoting in code.

There are some people who have the opinion that cross-tabs in the presentation layer are better performers.

.NET CrossTabs versus SQL Server CrossTabs
http://weblogs.sqlteam.com/jeffs/archive/2005/05/12/5127.aspx

Example:

CrossTab Performance Testing
http://weblogs.sqlteam.com/jeffs/articles/5124.aspx
Namespace CSharpConsole

Imports System.Data.SqlClient
Imports System.Data

    Class CrossTabTesting
        <STAThread()> _
        Private Shared Sub Main(ByVal args As String())
            Dim conn As SqlConnection
            Dim s As String
            Dim i As Integer

            conn = New SqlConnection("Server=(local);Database=Northwind;uid=xx;pwd=xx")
            conn.Open()

            Console.WriteLine("Beginning performance test for crosstab techniques." & vbLf)
            Console.WriteLine("Please enter the # of iterations to perform:")
            s = Console.ReadLine()
            Try
                i = Convert.ToInt32(s)
                Console.WriteLine(vbLf & "Testing dynamic SQL crosstab procedure....")
                Console.WriteLine("-- Result: {0} seconds." & vbLf, TestCrossTabDynamic(conn, i))
                Console.WriteLine("Testing static SQL crosstab procedure....")
                Console.WriteLine("-- Result: {0} seconds." & vbLf, TestCrossTabStatic(conn, i))
                Console.WriteLine("Testing C# crosstab transformation....")
                Console.WriteLine("-- Result: {0} seconds." & vbLf, TestPivotFunction(conn, i))
                Console.WriteLine(vbLf & "Testing complete.")
            Catch ex As Exception
                Console.WriteLine(vbLf & "Error: " & ex.Message)
                Console.WriteLine("Program aborted...")
            Finally
                conn.Close()
                Console.WriteLine(vbLf & "Press ENTER to quit.")
                Console.ReadLine()
            End Try
        End Sub

        Private Shared Function TestPivotFunction(ByVal conn As SqlConnection, ByVal iterations As Integer) As Integer
            Dim dt As DataTable

            Dim SQL As [String] = "select * from PivotTest order by CustomerID"
            Dim com As New SqlCommand(SQL, conn)

            Dim t As DateTime = DateTime.Now

            While System.Math.Max(System.Threading.Interlocked.Decrement(iterations), iterations + 1) > 0
                dt = Pivot(com.ExecuteReader(), "CustomerID", "ProductName", "Qty")
            End While

            Return DateTime.Now.Subtract(t).Seconds
        End Function

        Private Shared Function TestCrossTabDynamic(ByVal conn As SqlConnection, ByVal iterations As Integer) As Integer
            Dim da As SqlDataAdapter
            Dim dt As DataTable

            Dim SQL As String = "exec CrossTab2 'select * from PivotTest','ProductName','SUM(Qty)[]','CustomerID, CompanyName'"
            Dim com As New SqlCommand(SQL, conn)

            Dim t As DateTime = DateTime.Now

            While System.Math.Max(System.Threading.Interlocked.Decrement(iterations), iterations + 1) > 0
                dt = New DataTable()
                da = New SqlDataAdapter(com)
                da.Fill(dt)
            End While

            Return DateTime.Now.Subtract(t).Seconds
        End Function

        Private Shared Function TestCrossTabStatic(ByVal conn As SqlConnection, ByVal iterations As Integer) As Integer
            Dim da As SqlDataAdapter
            Dim dt As DataTable

            ' set the parameter so we get a SQL string only back that we can execute directly:
            Dim SQL As String = "exec CrossTab2 'select * from PivotTest','ProductName','SUM(Qty)[]','CustomerID, CompanyName',Null,1"

            Dim com As New SqlCommand(SQL, conn)

            SQL = com.ExecuteScalar().ToString()

            ' and set up the new SQL command, already written out and optimized and ready to go:
            com = New SqlCommand(SQL, conn)

            Dim t As DateTime = DateTime.Now

            While System.Math.Max(System.Threading.Interlocked.Decrement(iterations), iterations + 1) > 0
                dt = New DataTable()
                da = New SqlDataAdapter(com)
                da.Fill(dt)
            End While

            Return DateTime.Now.Subtract(t).Seconds
        End Function

        Public Shared Function Pivot(ByVal dataValues As IDataReader, ByVal keyColumn As String, ByVal pivotNameColumn As String, ByVal pivotValueColumn As String) As DataTable
            Dim tmp As New DataTable()
            Dim r As DataRow
            Dim LastKey As String = "//dummy//"
            Dim i As Integer, pValIndex As Integer, pNameIndex As Integer
            Dim s As String
            Dim FirstRow As Boolean = True

            ' Add non-pivot columns to the data table:

            pValIndex = dataValues.GetOrdinal(pivotValueColumn)
            pNameIndex = dataValues.GetOrdinal(pivotNameColumn)

            For i = 0 To dataValues.FieldCount - 1
                If i <> pValIndex AndAlso i <> pNameIndex Then
                    tmp.Columns.Add(dataValues.GetName(i), dataValues.GetFieldType(i))
                End If
            Next

            r = tmp.NewRow()

            ' now, fill up the table with the data:
            While dataValues.Read()
                ' see if we need to start a new row
                If dataValues(keyColumn).ToString() <> LastKey Then
                    ' if this isn't the very first row, we need to add the last one to the table
                    If Not FirstRow Then
                        tmp.Rows.Add(r)
                    End If
                    r = tmp.NewRow()
                    FirstRow = False
                    ' Add all non-pivot column values to the new row:
                    For i = 0 To dataValues.FieldCount - 3
                        r(i) = dataValues(tmp.Columns(i).ColumnName)
                    Next
                    LastKey = dataValues(keyColumn).ToString()
                End If
                ' assign the pivot values to the proper column; add new columns if needed:
                s = dataValues(pNameIndex).ToString()
                If Not tmp.Columns.Contains(s) Then
                    tmp.Columns.Add(s, dataValues.GetFieldType(pValIndex))
                End If
                r(s) = dataValues(pValIndex)
            End While

            ' add that final row to the datatable:
            tmp.Rows.Add(r)

            ' Close the DataReader
            dataValues.Close()

            ' and that's it!
            Return tmp
        End Function
    End Class
End Namespace

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
ASP.net produce a pdf from a GridView 2 33
DLL in ASP.NET 20 38
How do I get the id from URL? 19 46
Align Buttons next to each other 2 11
In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

772 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now