Products
Services
Contact Us

Scripts: C# :: Web controls :: Library Article #10

Developer's Section

Changing Cells in a GridView Dynamically
By: Erobo Team Member

Hire a Developer for Related Work / Installation | $55 hr
Rating:  | Rate It:   
Average Votes: (3063)
Favorites:

Learn to change cells of GridViews created from generic list dynamically by using onRowDataBound in C#.

In this tutorial we will look at a simple GridView control that uses the event OnRowDataBound to change the items within a cell dynamically after binding the data to the GridView. We will use a generic list to bind the data to a datagrid (List<T> Class).

In file myClientsList.aspx:

 Code Snippet 1

<%@ Control Language="C#" AutoEventWireup="true"
 CodeBehind="myClientsList.aspx.cs" Inherits="Dev.UserControls.myClientsList" %>


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
    OnRowDataBound="GridView1_DataBound" AutoGenerateSelectButton="false">
  <Columns>
    <asp:BoundField DataField="clientID" ShowHeader="false" Visible="false"  />
    <asp:BoundField DataField="isActive" ShowHeader="false" Visible="false"  />
    <asp:TemplateField >
      <HeaderTemplate>Client Name</HeaderTemplate>
        <ItemTemplate>
          <%#Eval("clientName") %>
        </ItemTemplate>
    </asp:TemplateField>
         
    <asp:TemplateField>
      <HeaderTemplate>Client Phone</HeaderTemplate>
        <ItemTemplate>
          <%#Eval("clientPhone") %>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:ButtonField ButtonType="Link"  HeaderText="Read" Text="" /> 
  </Columns>
</asp:GridView>



Note the method GridView1_DataBound will be called when the data is bound to the actual row. Now, in the code behind we will handle this method accordingly to modify, or delete fields.

In file myClientsList.aspx.cs:

 Code Snippet 2

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 Dev.UserControls
{
  public partial class myClientsList : System.Web.UI.Page
  {
     protected void Page_Load(object sender, EventArgs e)
     {
       BindGrid();
     }

     public void BindGrid()
     {

       List<ClientObject> lstClients = null;

       IDataReader dr = MyUtil.GetClientsFromStoredProc();

       bool isActive = false;

       lstClients = new List<ClientObject>();

       while (dr.Read())
       {
         if (Convert.ToString(dr["resgisOn"]) == "" || DBNull.Value == dr["resgisOn"])
         {
           isActive = false;
         }
         else
         {
           isActive = true;
         }

         lstClients.Add(new ClientObject(Convert.ToInt32(dr["clientID"]), 
                                         isActive, 
                                         Convert.ToString(dr["clientName"]),
                                         Convert.ToString(dr["clientPhone"])));
       }
       if (dr != null)
       {
         dr.Close();
       }
            
       GridView1.DataSource = lstClients;
       GridView1.DataBind();
       ViewState.Add("listClients", lstClients.ToArray());
     }

     [Serializable]
     public class ClientObject
     {

       private int clientid;
       public int clientID
       {
         get { return clientid; }
         set { clientid = value; }
       }

       private bool isactive;
       public bool isActive
       {
         get { return isactive; }
         set { isactive = value; }
       }

       private string clientname;
       public string clientName
       {
         get { return clientname; }
         set { subject = value; }
       }

       private string clientphone;
       public string clientPhone
       {
         get { return clientphone; }
         set { clientphone = value; }
       }

       public ClientObject(int clientID, bool isActive, string name, string phone, )
       {
         this.clientID = clientID;
         this.isActive = isActive;
         this.clientName = name;
         this.clientPhone = phone;
       }

     }

     protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
     {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
         ClientObject rowView = (ClientObject)e.Row.DataItem;

         LinkButton thisBtnField = null;

         if (rowView != null)
         {

           if (rowView.isActive == true)
           {
             e.Row.Cells[2].Text = "Active: " + e.Row.Cells[2].Text;

             thisBtnField = (LinkButton)e.Row.Cells[4].Controls[0];

             thisBtnField.Text = "Edit Active";
           }
           else if (rowView.isActive == false)
           {

             e.Row.Cells[2].Text = "InActive: " + e.Row.Cells[2].Text;

             thisBtnField = (LinkButton)e.Row.Cells[2].Controls[0];

             thisBtnField.Text = "Edit Inactive";
           }
         }
       }
     }
  }
}


Other operations such as delete cells using removeAt(), and columnSpan() are also available. I Hope this helps!.


See other Scripts in Web controls

Submit Your Scripts:


System Message:
  • Your C# script has been sent. Please allow 48 hours for processing.


If you would like to have your Javascripts published in this section please fill out
the form below:
*Your Name or Username:
Home Town:
*Email:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]