Merge two Data Column and bind GridView in ASP.NET

In this article, I will show you how to merge two data column into single one. First of all, bind DataTable with four columns i.e SNO, FirstName, LastName and City. Bind the DataTable source with GridView. Now, You can change the binding view of Gridview using OnRowDataBound event.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default12.aspx.cs" Inherits="Default12" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView runat="server" ID="g1" AutoGenerateColumns="false" OnRowDataBound="g1_RowDataBound">

        <Columns>

            <asp:BoundField DataField="SNO" HeaderText="Serial Number" />
            <asp:BoundField DataField="" HeaderText="Name(First+Last)" />
            <asp:BoundField DataField="City" HeaderText ="City" />

        </Columns>


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



Code Behind Code

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default12 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[4] { new DataColumn("SNO"), new DataColumn("FirstName"), new DataColumn("LastName"), new DataColumn("City") });
            dt.Rows.Add(1, "jacob ", "lefore", "New York");
            dt.Rows.Add(2, "Bill ", "Smith", "US1");
            dt.Rows.Add(3, "Smith ", "Bill", "US2");
            dt.Rows.Add(4, "Ammey ", "Bella", "US3");
            g1.DataSource = dt;
            g1.DataBind();
        }

    }
    protected void g1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[1].Text = string.Format("{0}-{1}", DataBinder.Eval(e.Row.DataItem, "FirstName"), DataBinder.Eval(e.Row.DataItem, "LastName"));
        }
    }
}

Comments

Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites