Bind CheckBox in ASP.NET GridView – Multiple ways

Continuing my ASP.NET GridView Tips and Tricks series, this post shows how to bind the Checkbox in an ASP.NET GridView.

You may have columns in your database that represents status, like 0 or 1. They are usually represented using the ‘Bit’ datatype in SQL Server For eg: The Discontinued column in the Products table of the Northwind database. If you are binding the GridView to such a column via a DataSource, you can use the CheckBoxField to bind to bit datatypes, as shown below

<asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued"
SortExpression="Discontinued" />

Bind CheckBox to a Column which has data in ‘Yes’ or ‘No’ format

However, at times developers use ‘Yes’ or ‘No’ in their tables to represent status. In such cases, here’s how to use the ItemTemplate to bind a Checkbox in an ASP.NET GridView

CheckBox GridView

As you can see, we are using a DataBinding expression and calling the Eval() method. Behind the scenes, the Eval() method calls the static DataBinder.Eval() method and uses reflection to find the column name. If you want to avoid using reflection, use the following code:

CheckBox GridView






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

healthdurbar com said...

this is an interesting information...good post