Tuesday 7 April 2015

ASP.NET - GridView with word wrap - Ensure words are not overlapping

Watch this example on YouTube

StyleSheet

.GridView{
    word-wrap: break-word;
}

HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewWordWrap.aspx.cs" Inherits="WebApplication1.GridViewWordWrap" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="StyleSheet2.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" CssClass="GridView" runat="server" AutoGenerateColumns="false" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server"
                            Text='<%# Bind("Name") %>' Width="100px"
                            ></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("Age") %>' Width="100px"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>

        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;

namespace WebApplication1
{
    public partial class GridViewWordWrap : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = LoadData();
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

        protected DataTable LoadData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Age");
            dt.Rows.Add(new object[] { "FrankVeryLoooooooooooooooooooooooooooooong", "33AgeVeryLooooooooooooooooooooong" });
            dt.Rows.Add(new object[] { "BobVeryLoooooooooooooooooooooooooooooong", "44AgeVeryLooooooooooooooooooooong" });
            dt.Rows.Add(new object[] { "JohndkVeryLoooooooooooooooooooooooooooooong", "55AgeVeryLooooooooooooooooooooong" });
            dt.Rows.Add(new object[] { "TarasVeryLoooooooooooooooooooooooooooooong", "66AgeVeryLooooooooooooooooooooong" });
            dt.Rows.Add(new object[] { "IvanVeryLoooooooooooooooooooooooooooooong", "77AgeVeryLooooooooooooooooooooong" });
            dt.Rows.Add(new object[] { "LesiaVeryLoooooooooooooooooooooooooooooong", "88AgeVeryLooooooooooooooooooooong" });
            return dt;
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

No comments:

Post a Comment