11/02/2011

Bind DataTable to Gridview

This is an example of Creating new DataTable, Add Array to DataTable, Bind to GridView, and add text to LinkButton and Label to Gridview from Code Behind.

First, Create new DataTable.
Second, Add new DataColumn.
Third, Add new DataRow.
Forth, Add Array to DataTable.
Fifth, Bind DataTable to GridView.
Sixth, Add Text to LinkButton and Label.
Finally, Add PostBack Url to the LinkButton and send parameter to other page.

.aspx page

<asp:GridView ID="grdName" runat="server" GridLines="None" AutoGenerateColumns="False">

<Columns>

            <asp:TemplateField HeaderText="Firstname">

            <ItemTemplate>

                      <asp:LinkButton ID="lnkFirstName" runat="server">LinkButton</asp:LinkButton>

            </ItemTemplate>

            </asp:TemplateField>

            <asp:TemplateField HeaderText="Lastname">

            <ItemTemplate>

                      <asp:Label ID="lblLastName" runat="server" Text="Label"></asp:Label>

            </ItemTemplate>

            </asp:TemplateField>

</Columns>

</asp:GridView>

.aspx.cs page


//    you can add this code to the method which you want to create the DataTable and Bind the GridView

//create new DataTable

DataTable dt = new DataTable();

//create new DataColumn
DataColumn newColumn;

newColumn = new DataColumn();

//add type of the column
newColumn.DataType = Type.GetType("System.String");

//add column name
newColumn.ColumnName = "Firstname";

//add column to the DataTable
dt.Columns.Add(newColumn);

newColumn = new DataColumn();

newColumn.DataType = Type.GetType("System.String");

newColumn.ColumnName = "Lastname";

dt.Columns.Add(newColumn);

//create new row
DataRow newRow;

//assume that you have 2 ArrayList which are equal length
//convert ArrayList to Array

arrayFn = arrayListFn.ToArray();
arrayLn = arrayListLn.ToArray();

//add row to DataTable
for (int i = 0; i < arrayFn.Length; i++)

{

      newRow = dt.NewRow();

      string fn = arrayFn.GetValue(i).ToString();

      string ln = arrayLn.GetValue(i).ToString();

      newRow[0] = fn;

      newRow[1] = ln;

      dt.Rows.Add(newRow);

}


//bind DataTable to GridView
grdName.DataSource = dt;

grdName.DataBind();


//add text to LinkButton and Label
for (int i = 0; i < grdName.Rows.Count; i++)

{

      string fn = dt.Rows[i][0].ToString();

      string ln = dt.Rows[i][1].ToString();

      LinkButton lnkFn = (LinkButton)grdName.Rows[i].FindControl("lnkFirstName");

      lnkFn.Text = fn;

      Label lblLn = (Label)grdName.Rows[i].FindControl("lblLastName");

      lblLn.Text = ln;

     
//add PostBack Url and sending parameter to other page     
lnkFn.PostBackUrl = "~/showName.aspx?firstname=" + fn;

}