Solved

Gridview - Matrix format

Posted on 2011-03-03
3
1,337 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
ID: 35036335
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
ID: 35036981
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
ID: 35070827
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

685 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