How to add a value to asp:Checkbox control and retrieve it on postback?

The <asp:Checkbox> is one of those controls in ASP.NET which does not have a default Value property in which you can store a value and retrieve it upon postback. This becomes a problem in cases where the value has to be saved into the database or an action depends on the condition of that value.

There are several workarounds and depending on your coding acumen you can even develop your own but we will stick to the simplest here.

You can use the InputAttributes collection in the Checkbox control. You can add a value to the Checkbox as follows:

Suppose chkTest is the ID of the checkbox. You can set its value through the following code

chkTest.InputAttributes.Add(“value”,”Adeel”);

Refresh the page and view the source of the page. There you will find the value attribute in the chkTest checkbox code.

If you would like to retrieve the value of the checkbox on postback then use the following code.

Response.Write(chkTest.Attributes[“value”].toString());

Hope the above helps.

Leave a Comment