Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom attributes to ASP.NET controls

I've got an ASP.NET control say checkbox:

<asp:CheckBox ID="myChck" runat="server" Value="myCustomValue" />

Is it possible to add this custom Value attribute from code-behind and respectively get the value from Value

Something like (psuedocode):

myCkck.Value = "blq blq";
string chckValue = myChck.Value;

How can I do this?

like image 849
Anton Belev Avatar asked Jul 25 '13 12:07

Anton Belev


People also ask

Can we create custom attributes in C#?

AttributeUsage has a named parameter, AllowMultiple , with which you can make a custom attribute single-use or multiuse. In the following code example, a multiuse attribute is created. In the following code example, multiple attributes of the same type are applied to a class.

What is custom attribute in C#?

Attributes are used to impose conditions or to increase the efficiency of a piece of code. There are built-in attributes present in C# but programmers may create their own attributes, such attributes are called Custom attributes. To create custom attributes we must construct classes that derive from the System.

What are custom attributes?

A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.


2 Answers

It's perfectly possible:

myCkck.Attributes.Add("Value", "blq blq");

string chckValue = myChck.Attributes["Value"].ToString();
like image 138
melancia Avatar answered Sep 20 '22 20:09

melancia


You could create a new class that inherits the CheckBox class (or any other control class for that matter) and add any further properties you need to the derived class. That way you would get an extended CheckBox more or less.

public class ExtendedCheckBox : CheckBox
{
    public string Value
    {
        get;
        set;
    }

    public ExtendedCheckBox : base()
    {

    }
}
like image 30
KnaperKrisp Avatar answered Sep 22 '22 20:09

KnaperKrisp