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.

    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

  /// <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

Instead of 1/0 you can use “Yes/No”  or whatever value you want instead of Checkbox. Thumbs up

\

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

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

Comments are closed.