Solved

Gridview - Matrix format

Posted on 2011-03-03
3
1,320 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
ASP.NET e-commerce website 4 60
SQL best practice question 3 36
Entity Framework 3 48
Asp.net mvc foreach 3 35
This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

863 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

20 Experts available now in Live!

Get 1:1 Help Now