How to Display “Yes” or “No” Instead of Checkbox while binding Boolean value with GridView ?

If you are binding some data source in grid view which having any field type of Boolean then Grid View Rendered it as “Checkbox” . But sometime we may required to display either Yes/ No or “1/0” instead of Checked/ Unchecked Text Box.   Here is an quick tip which described how you can override the checkbox to your required  value in  GridView RowDataBound events.

Let’s consider you have a simple class “Student” with some student records.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
Public Class Student
{
    Public Int Roll { Get; Set; }
    Public String Name { Get; Set; }
    Public Bool Status { Get; Set; }
}
    Protected Void Page_Load(Object Sender, EventArgs E)
{
   List<Student> Students = New List<Student>();
   Students.Add(New Student { Roll = 1, Name = "Abhijit", Status=True});
   Students.Add(New Student {Roll=2,Name="Manish",Status=False});
   Students.Add(New Student { Roll = 3, Name = "Atul", Status = True });
   GridView2.DataSource = Students;
   GridView2.DataBind();
}

Now if you run the application you will get below out put Which is the default behavior of GridView

clip_image001

Now Change the binding during on RowDataBound  of GridView

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
/// <Summary>
  /// Handles The RowDataBound Event Of The GridView2 Control.
  /// </Summary>
  /// <Param Name="Sender">The Source Of The Event.</Param>
  /// <Param Name="E">The <See Cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> Instance Containing The Event Data.</Param>
  Protected Void GridView2_RowDataBound(Object Sender, GridViewRowEventArgs E)
  {
      If (E.Row.RowType == DataControlRowType.DataRow)
      {
          Student S = (Student)E.Row.DataItem;
          If (S.Status == True)
          {
              E.Row.Cells[2].Text = "1";
          }
          Else
          {
              E.Row.Cells[2].Text = "0";
          }
      }
  }

Now if you run the application, your output will be looks like below.

clip_image003

Posted in Hosting Article.