Show GridView Data in Left to Right manner

Show GridView Data in Left to Right manner

The GridView by default shows the data from ‘top to bottom’. If you want to show the data from left to right then you can use JavaScript to do this work. Here in this tutorial I will use JavaScript to swap the GridView’s Rows and Columns to bring 2 changes:

  • 1. The column name displays vertically on the left edge.
  • 2. The values of the columns will show horizontally against them.

The first image shows the GridView with default column layouts (Top to Bottom):

Default GridView

The second image shows the GridView with columns shown vertically (Left to Right):

GridView with Vertical Columns
Want to learn ASP.NET Core from the start? Do check my 100+ tutorials written on this topic. Link – ASP.NET Core Tutorials

The GridView code

I have a GridView that shows some product information. There are 5 columns:

  • 1. Id
  • 2. Name
  • 3. Quantity
  • 4. Price
  • 5. Edit

The GridView code is shown below:

<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label ID="nameLabel" runat="server" Text='<%#Bind("Name") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Quantity">
            <ItemTemplate>
                <asp:Label ID="TxtQuantity" runat="server" Text='<%# Bind("Quantity") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Price">
            <ItemTemplate>
                $<asp:Label ID="TxtPrice" runat="server" Text='<%# Bind("Price") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Edit" ItemStyle-CssClass="editColumn">
            <ItemTemplate>
                <asp:Button ID="editButton" runat="server" Text="Edit"></asp:Button>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Next, I bind the GridView with some dummy data in the .aspx.cs page. The code for this is:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        BindGridView();
}

public void BindGridView()
{
    DataTable dataTable = new DataTable();
    DataColumn[] dataColumn = new DataColumn[]
    {
            new DataColumn("Id"),
            new DataColumn("Name"),
            new DataColumn("Quantity"),
            new DataColumn("Price")
    };

    dataTable.Columns.AddRange(dataColumn);
    dataTable.Rows.Add(new object[] { 1, "Pants", 5, 10 });
    dataTable.Rows.Add(new object[] { 2, "Shirts", 6, 5 });
    dataTable.Rows.Add(new object[] { 3, "Shoes", 7, 8 });
    dataTable.Rows.Add(new object[] { 4, "Socks", 8, 9 });
    dataTable.Rows.Add(new object[] { 5, "TVs", 4, 99 });
    dataTable.Rows.Add(new object[] { 6, "CDs", 5, 2 });
    dataTable.Rows.Add(new object[] { 7, "Keyboards", 8, 3 });
    dataTable.Rows.Add(new object[] { 8, "Mouses", 3, 5 });

    gridView.DataSource = dataTable;
    gridView.DataBind();
}

Also add some CSS style for giving green background color to the columns name and blue background color to the column values of the GridView, like shown below:

table {
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

    table td, table th {
        border: 1px solid #ddd;
        padding: 8px;
    }

    table tr {
        background-color: #2549f6;
    }

    table th {
        padding-top: 12px;
        padding-bottom: 12px;
        text-align: left;
        background-color: #4CAF50;
        color: white;
    }

The JavaScript code

Now I have to add the JavaScript code that will change the alignment of the GridView columns i.e. showing them from Left to Right. For this add a button that will call a JavaScript function called Swap().
<button class="swap" onclick="return Swap();">Swap</button>

Next, add the Swap() function inside the script tag in your web page like this:

<script>
    function Swap() {
        var t = document.getElementsByTagName('tbody')[0],
            r = t.getElementsByTagName('tr');
        table = document.createElement("table");

        for (i = 0; i < r.length; i++) {
            for (j = 0; j < r[i].querySelectorAll('th,td').length; j++) {
                if (i == 0) {
                    tem = document.createElement("tr");
                    clone = r[i].querySelectorAll('th,td')[j].cloneNode(true);
                    tem.appendChild(clone);
                    table.appendChild(tem)
                }
                else {
                    clone = r[i].querySelectorAll('th,td')[j].cloneNode(true);
                    table.getElementsByTagName("tr")[j].appendChild(clone);
                }
            }
        }
        document.getElementById("gridView").innerHTML = table.innerHTML;
        return false;
    }
</script>

Explanation: The GridView is rendered as an HTML Table in the browser. So I have used getElementsByTagName(‘tbody’) and getElementsByTagName(‘tr’) to get the tbody and tr elements of the GridView.

Important JavaScript Tutorial: Learn JavaScript Promise method in easiest way

I have created a new table in the code like – table = document.createElement(“table”). This table will contain the changed orientation of the GridView (Left to Right), and will replace the original GridView at the end.

Then I am looping through each of GridViews column using the 2 for loops. The outer one loops through each tr element of the GridView and the inner loop is used for looping through each td element that is inside the tr element.

for (i = 0; i < r.length; i++) {
    for (j = 0; j < r[i].querySelectorAll('th,td').length; j++) {
    //…
    }
}

Inside these for loops I am creating a new table with the changed orientation.

Finally at the last I am replacing the current GridView’s HTML with the new Table:

document.getElementById("gridView").innerHTML = table.innerHTML;

Refer the links to DEMO / DOWNLOAD Codes:

DEMO DOWNLOAD

Conclusion

I hope you like the JavaScript approach to change the GridView orientation from ‘Top to Bottom’ to Left to Right. JavaScript approach is not only simple but also very fast to do all such works in your web page.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.

Leave a Reply

Your email address will not be published. Required fields are marked *