Why the NumericUpDown's Text property is not suggested by Intellisense? - c#

I have noticed that all Controls have a Text property. However, the Intellisense doesn't suggest it for NumericUpDown objects. When manually writing it down, it does work and returns the value of the NumericUpDown as a string. Why is that?

The docs show the property defined as:
[BrowsableAttribute(false)]
[BindableAttribute(false)]
public override string Text { get; set; }
The BrowsableAttribute(false) bit (or more likely EditorBrowsableAttribute) is what 'hides' it from Intellisense.
Why does it hide it?
This API supports the product infrastructure and is not intended to be
used directly from your code.

Related

Add code to C# get/set of property without needing backing field?

You know how you can have a property that automatically generates a backing field? Like if I go:
public String SomeProperty {get; set;}
I know that if I want to add code to that property I have to create the backing field as so:
public string someProperty = string.Empty;
public string SomeProperty
{
get { return someProperty; }
set
{
someProperty = value;
DoSomething();
}
}
Basically, what I want to know is... is there any way to do this but without having to create the backing field? For example I could use it to trigger some kind of event that occurs when a property is set. I'm looking for something like this:
public string SomeProperty
{
get;
set { this.OnSomeEvent; }
}
But I know that'll cause a compile error because get needs do declare a body if set does.
I've researched and I cant find anything, but I thought I'd check to see if anyone knew.
I guess what I'm really after is some way to trigger an event when a property is changed but without having to add all that extra clutter. Any suggestions?
Simple answer is no, you can't have it both ways. From .NET Docs:
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.
There are not any solutions for this built into the framework, and you cannot modify existing types via reflection (in order to add the logic at runtime). The only way to accomplish this seems to be at compile time.
There is a product http://www.postsharp.net/ that can accomplish this (intercept property/method calls), and there does appear to be a free edition.
The field keyword might be added to C#, see https://github.com/dotnet/csharplang/issues/140, which removes "when no additional logic" requirement for auto properties.
It didn't make it into C# 10 nor 11, but latest comment from compiler team says C# version 12 might have it. They release yearly, so that would be Nov 2023.

DataType vs UiHint

I have been using mvc2 for a while now, and when i need to set the template i use the DataType Attribute
[DataType("DropDown")]
public int Field { get; set; }
I see others using UiHint to achieve the same results
[UiHint("DropDown")]
public int Field { get; set; }
What is the difference between using these two attributes? Which attribute should I be normally using, or are they for different tasks?
DataType is generally used to make it known that this is a very specific version of a property, such as price.
The most common example of DataType is the [DataType(DataTypes.EmailAddress)] which usually is a string but we're saying that this is a very specific type of string.
They're both helpful and the UIHint overrides the DataType. So if you have a certain DataType but you want to override the editor for that specific property you can use a UIHint.
DataType attribute has two purposes
Provide additional type information for a data field. You do this by applying the DataTypeAttribute attribute to a data field in the data model and by specifying the additional type name from the DataType enumeration. Then the view engine uses the default template for displaying the property, like, a checkbox for a boolean.
If you want to override the default template, and wish to use a custom template, then it can be used to associate a custom field template with that data field. In this case you must provide a partial page[.cshtml, MVC 4] to describe the display.
The purpose of UIHint is exactly same as the second point above.
Where to use what? The answer is: context, ie., what will make more sense, what is closer to the physical problem your code is trying to solve.
What if both are applied to the same property? The answer is: UIHint has precedence, obviously. But why would you apply both?

What does square bracket [] mean in the below code?

I got below code from http://msdn.microsoft.com/en-us/library/dd584174(office.11).aspx for adding custom property in webpart tool pane. What does square bracket ([]) mean in the below code?
[Category("Custom Properties")]
[WebPartStorage(Storage.Personal)]
[FriendlyNameAttribute("Custom Color")]
[Description("Select a color from the dropdown list.")]
[Browsable(true)]
[XmlElement(typeof(System.Drawing.KnownColor))]
public System.Drawing.KnownColor MyColor
{
get
{
return _myColor;
}
set
{
_myColor = value;
}
}
As #Spencer Ruport said, they're attributes. They're used within .NET for declarative programming.
You can find information on each of these attributes at MSDN. However, you should know that the name of the attribute can be shortened. In your case, for example, Category is the short form of the class name CategoryAttribute and XmlElement is the short form of the class name XmlElementAttribute. When declaring attributes, the Attribute portion of the class name can be left out.
I've used most of these attributes in conjunction with the PropertyGrid control (see here for an example), although in your case, they are used for a Web Part property pane. The purpose is still the same. The attributes are used by the control to know how to display the property to the user. By using a combination of the various attributes that the control understands, it is possible to declaratively dictate this behavior.
I hope that helps a little bit, but Spencer is correct, you'll learn a lot more reading about attributes via Google than I can explain here.
They're called attributes.
Here's a quick example of how they can be used: http://www.codeproject.com/KB/cs/attributes.aspx

DesignOnly attribute does not hide a property in runtime

I'm building a custom web control with a public property which I only want to be available in design time (i.e. make it unavailable in code behind).
The DesignOnly attribute promises to do just that, but when I set [DesignOnly(true)] it has no noticeable effect whatsoever:
[Bindable(true)]
[Category("Appearance")]
[DefaultValue(null)]
[Localizable(false)]
[DesignOnly(true)]
public string MyProp
{
get
{
return ViewState["MyProp"] as string;
}
set
{
ViewState["MyProp"] = value;
}
}
The property still appears in code behind IntelliSense. Setting a value to it in code behind works. In these respects, the behavior is just as if the attribute had never been set. And I've cleaned and rebuilt the complete solution. Twice.
Am I doing it wrong? Can you please tell me what is the right way to go about this, then?
Many thanks in advance.
The DesignOnly attribute promises to do just that
Actually, no; it tries to make it clear when accessing it in code isn't available; if you lie (i.e. claim that something is design-only when it is available) then you should expect it to misbehave. The compiler knows what is available, and this design-only attribute is not defined in the C# spec, so it makes no difference to the compiler if you add this attribute.
Try adding:
[EditorBrowsable(EditorBrowsableState.Never)]
which the code editor (IDE) looks at (but only when using a separate assembly) - note that this doesn't stop you using it - it just hides it.
I believe the MSDN text is trying to describe the difference between properties that actually exist on code, vs properties that only pretend to exist; you can actually do all sorts of things to make fake properties appear in the designer, and it is these pretend properties that might be marked as design-only.

Dynamic options dialog (using reflection)

Does anyone know of a good component (C# WinForms) which would allow creating an options (settings) form, given a custom class with a bunch of properties? I am not looking for something shiny, but something merely better than a property grid. I can easily take care of the visual part, but I simply don't want to lose time doing reflection to add and bind controls if it already exists.
I am pretty sure I've seen a Visual Studio options-like form somewhere before, which was created dynamically (with some attributes attached to the properties of the class, to allow grouping and additional info).
[Edit] For example, I might have an options class:
public class Options : SerializableOptions<Options>
{
[Category("General")]
[Name("User name")]
[Description("Some text")]
public string Username { get; set; }
[Category("General")]
[Name("Log in automatically")]
public bool LogInAutomatically { get; set; }
[Category("Advanced")]
// ConnectionType is enum
public ConnectionType ConnectionType { get; set; }
// ...
}
After passing it to this form, it would create two panels ("General" and "Advanced"), with a CheckBox and a TextBox on the first panel, and one ComboBox (with all available enums) on the second panel.
If there isn't such a control, what do you guys use? Manually add, populate, format and bind controls for each option?
I'm not aware of any controls that allow you to do this, but it isn't difficult to do yourself. The easiest way is to create the dialog shell, a user control which acts as the base class for the options "panels", one (or more) attribute to control the name and grouping information, and an interface (which the user control implements).
Each of your custom options panels derives from the user control and overrides some sort of Initialize() and Save() method (provided by the user control). It also provides your attribute (or attributes) that determine the name/grouping information.
In the dialog shell, reflectively inspect all public types from your assembly (or all loaded assemblies) looking for types that implement your interface. As you find a type, get the attributes to determine where to place it in your grouping (easiest thing here is to use a tree view), call Activator.CreateInstance to create an instance of the user control and store it in the Tag property. When the user clicks on an entry in the grouping (a tree node), get the Tag and set the panel which contains the user control to the object in the Tag property. Finally, when the user clicks "OK" on the dialog, loop through the tree nodes, get the Tag property and call the Save method.
Update:
Another option would be to use a property grid control. It doesn't have a "pretty" UI look to it, but it is very functional, already supports grouping by a category attribute, and allows a great deal of flexibility. You could go with a single property grid that shows all of the options, or go with a "hybrid" approach with a tree view that groups by major functions (plugin, capability, etc.), probably based on the type. When the user clicks that node, give the property grid the object instance. The only drawback to this approach is that when changes are made to the property grid values they are "live" in that the underlying property is immediately changed, which means there is no concept of "Cancel" short of saving a copy of each value that could change and performing some type of "reset" yourself.
I don't know if such a control exists, but writing the required reflection code is really not that hard. E.g. something like this:
// the class for which to create an UI
public class MyClass
{
public string Text { get; set; }
public int ID { get; set; }
}
...
// basic reflection code to build the UI for an object
var obj = new MyClass() { Text="some text", ID=3};
foreach (var pi in obj.GetType().GetProperties())
{
var name = pi.Name;
var type = pi.PropertyType;
var value = pi.GetValue(obj, null);
//now setup the UI control for this property and display the value
}
I accidentally found something similar to this, I remebered that I had this problem a while ago and thought I should share it.
Here is a simple example: http://blog.denouter.net/2008/08/simple-reflection-form.html. It uses reflection to create several controls based on object's properties.

Categories