Getting the "value" property of a control - c#

I have a method that has a Control parameter. I want to get the value of the control. So if it is a TextBox get the value of the Text property; if it is a NumericUpDown get the value of the Value property and so on.
The problem is that I cannot write something like this:
Method(Control control)
{
control.Text;
}
or
Method(Control control)
{
control.Value;
}
Because there is no guarantee that the control has one of these properties, and what is its name if it does have it.
Is there a way to do something like that?

There isn't such common Value property in Control class.
You should use some if/else or switch/case or a dictionary approach to get the value from the control. Because you know what property you need. The control just provides properties.
For example for a ComboBox, what is the value? Is it SelectedItem, SelectedIndex, SelectedValue, Text? It's usage/opinion based.
The nearest thing to what you are looking for, is relying on DefaultProperty attribute of controls to get the value from that property using relfection. For example, having this method:
public object GetDefaultPropertyValue(Control c)
{
var defaultPropertyAttribute = c.GetType().GetCustomAttributes(true)
.OfType<DefaultPropertyAttribute>().FirstOrDefault();
var defaultProperty = defaultPropertyAttribute.Name;
return c.GetType().GetProperty(defaultProperty).GetValue(c);
}
You can get values this way:
var controls = new List<Control> {
new Button() { Text = "button1" },
new NumericUpDown() { Value = 5 },
new TextBox() { Text = "some text" },
new CheckBox() { Checked = true }
};
var values = controls.Select(x => GetDefaultPropertyValue(x)).ToList();

Related

C# - How do I set the selected item in a combobox by comparing my int value?

I'm using a ComboBox with items having text and value. Now, I want to simply make an item selected by comparing its value with the provided value. I'm iterating through the items and comparing as follow. Below code works fine, but is there a better or more simpler way to do this? I found a possible duplicate here but it works with the string value not integer.
foreach (ComboboxItem item in this.CampaignList.Items)
{
if (Convert.ToInt16(item.Value) == objAACampaign.CompanyId)
{
this.CampaignList.SelectedIndex = this.CampaignList.Items.IndexOf(item);
break;
}
}
Use display and value memeber
Create custom class like this:
class MyCustomClass
{
//important to have get set part
public _int { get; set; }
public _string { get; set; }
}
now load data you want to display inside List<MyCustomClass>() and then bind that list to combobox and set it's display and value member like this:
myComboBox.DisplayMember = "_string";
myComboBox.ValueMember = "_int";
myComboBox.DataSource = myList; //this is List<MyCustomClass>
Now simply use myComboBox.SelectedValue = valueYouWant
IMPORTANT!!!
Declare displayMember and valueMember before binding datasource to combobox because of perfomance. Search internet for more info.

Using C#, how can I create invisible property on listbox item and access it?

I'm using C# Windows Forms, and I have created a listbox and I want to create a value within each individual item in this listbox that is not visible. So to do this I have choosen to use the Display Member. There is only one problem. The name of the item I create that is visible to the user, in the listBox, is not the DisplayMember in the code which is "Item Name". Instead the name of the Item I create appears as "Doc_Engine.PersonalMessageSystemForm+SomeData".
Here is my first code:
//Create an item in the listBox1.
List<SomeData> data = new List<SomeData>();
data.Add(new SomeData() { Value = 1, Text = "Hidden Text" });
listBox1.DataSource = data;
listBox1.DisplayMember = "Item Name";
And here is my second code:
//A class that contains two required strings.
public class SomeData
{
public int Value { get; set; }
public string Text { get; set; }
}
Click here to see a picture of my ListBox
I want the name of my Item in the listbox to be "Item Name". Not "Doc_Engine.PersonalMessageSystemForm+SomeData".
Update: I might use the Tag property instead. But when I do this, the same thing happens. The name of the item does not turn out as desired.
Your SomeData class doesn't have a member called Item Name. It has two members: Value and Text. So, per the docs you get the result of calling ToString instead:
If the specified property does not exist on the object or the value of DisplayMember is an empty string (""), the results of the object's ToString method are displayed instead.
Change it to Value or Text or add some other property to hold the value you want to display.
In winforms controls there is a Tag property you can set to anything you want and later retrieve. Try using that instead.

Setting the start value of an enum ComboBox

been searching for a solution for this problem, found plenty solutions, but nothing changed my code's behaviour. This is in WinForms.
I am loading a form with a ComboBox, that contains the values and names of this enum, that is inside a class named "Node".
class Node
{
public enum NodeType { Yield, Home, Parking, Light, None, Inbound, Outbound }
public NodeType Type;
}
Then in my form, I have a ComboBox named "Type", which is set up like so (from the constructor):
Node node = new Node();
node.Type = Node.NodeType.Home;
Type = new ComboBox();
Type.Location = new Point(77, 41);
Type.Size = new Size(121, 24);
Type.DropDownStyle = ComboBoxStyle.DropDownList;
Type.DisplayMember = "Name";
Type.ValueMember = "Value";
Type.DataSource = Enum.GetValues(typeof(Node.NodeType));
Type.SelectedValue = node.Type;
Controls.Add(Type);
When the program runs, the list shows all the names, and on closing the form I am able to retrieve the selected value via. Type.SelectedValue. My problem is that the ComboBox doesn't start at the value that the Node is already set at. Essentially the line
Type.SelectedValue = node.Type;
doesn't do anything. I've tried using SelectedItem which didn't change anything, and
Type.SelectedIndex = (int)node.Type;
Which caused an ArgumentOutOfRangeException.
So, my question is: how do I set the start value of the ComboBox?
There are several mistakes in that code.
First, enum does not have Name and Value properties (in fact it does not have any property), so DisplayMember and ValueMember cannot be used and should be left blank (default). Which in turn means SelectedValue cannot be used and you need to use SelectedItem instead.
Second, you are using list data bound mode for the list portion of your ComboBox by setting DataSource property instead of populating Items, which is fine, but data binding occurs later in the process, so inside the constructor the Items property is empty and SelectedItem has no effect. In order to fix that, you need to move the data initialization part to your form Load event.
So, in your form constructor you'll have this:
Type = new ComboBox();
Type.Location = new Point(77, 41);
Type.Size = new Size(121, 24);
Type.DropDownStyle = ComboBoxStyle.DropDownList;
Controls.Add(Type);
and in your form Load event - this:
Node node = new Node();
node.Type = Node.NodeType.Home;
Type.DataSource = Enum.GetValues(typeof(Node.NodeType));
Type.SelectedItem = node.Type;
Type.SelectedIndex = index from your enum, for example the enum is {"apple", "pear", "pineapple"}, and you want pear by deafult, so Type.SelectedIndex = 1

How to get Control Value Form Control ID asp.net C#?

I have my page fills controls dynamically So All I can get is Control ID
So how can I get control Value or name from control ID
I tried this but nothing I get
TextBox control = new TextBox { ID = _NumberFieldID + item.BlueprintFieldId, CausesValidation = true, EnableViewState = true, CssClass = "form-control ui-spinner-input spin metadatacontrol", Width = new Unit(ctrWidth + "%") };
ctrlDivSet.Controls.Add(control);
and that is my experiment
Control ControlValues= FindControl(_NumberFieldID + validationObject.MatchBlueprintFieldId);
I tried to compare two controls values
So I used this
CompareValidator controlValidator = new CompareValidator()
{
ControlToValidate = control.ID,
ControlToCompare = _NumberFieldID + validationObject.MatchBlueprintFieldId,
Operator = voperator,
ValidationGroup = _ValidationGroup,
};
CotrolTOCompare can take the ID and compare its value
I need somthing like that
to obtain control name or value by its ID
please help
Im a bit confused as to what you want so let's start from here and then I'll update to address if it's not correct :)
To get a value you can use in for ex. JavaScript you can do
var clientId = myTextBox.ClientId;
If you want to use the name to get the control
var textBox = (TextBox)FindControl("myTextBox");

How to set selectedValue to Controls.Combobox in c#?

I have a combobox and I see that I am not able to set SelectedValue like this:
cmbA.SelectedValue = "asd"
So I tried to do this
cmbA.SelectedIndex = cmbA.FindString("asd");
Based on How to set selected value from Combobox?
I realised that my combobox is a System.Windows.Controls.ComboBox and not a System.Windows.Forms.ComboBox.
That means that FindString() is not available.
Based on User Control vs. Windows Form I get that forms are the container for controls, but I dont get why the Controls.ComboBox does not implement FindString().
Do I have to write my own code to do what FindString() does for Forms.ComboBox?
WPF ComboBoxes are not the same as WinForms ones. They can display a collection of objects, instead of just strings.
Lets say for example if I had
myComboBox.ItemsSource = new List<string> { "One", "Two", "Three" };
I could just use the following line of code to set the SelectedItem
myComboBox.SelectedItem = "Two";
We're not limited to just strings here. I could also say I want to bind my ComboBox to a List<MyCustomClass>, and I want to set the ComboBox.SelectedItem to a MyCustomClass object.
For example,
List<MyCustomClass> data = new List<MyCustomClass>
{
new MyCustomClass() { Id = 1, Name = "One" },
new MyCustomClass() { Id = 2, Name = "Two" },
new MyCustomClass() { Id = 3, Name = "Three" }
};
myComboBox.ItemsSource = data;
myComboBox.SelectedItem = data[0];
I could also tell WPF I want to consider the Id property on MyCustomClass to be the identifying property, and I want to set MyCombbox.SelectedValue = 2, and it will know to find the MyCustomClass object with the .Id property of 2, and set it as selected.
myComboBox.SelectedValuePath = "Id";
myComboBox.SelectedValue = 2;
I could even set the Display Text to use a different property using
myComboBox.DisplayMemberPath = "Name";
To summarize, WPF ComboBoxes work with more than just Strings, and because of the expanded capabilities, FindString is not needed. What you are most likely looking for is to set the SelectedItem to one of the objects that exist in your ItemsSource collection.
And if you're not using ItemsSource, then a standard for-each loop should work too
foreach(ComboBoxItem item in myComboBox.Items)
{
if (item.Content == valueToFind)
myComboBox.SelectedItem = item;
}
I don't know what you are trying to do but I think it would be easier to just do
cmbA.Text = "String";
That way you get your selected item
Else I found an intersting article that could help you out:
Difference between SelectedItem, SelectedValue and SelectedValuePath

Categories