Setting drop down value in unity with a string - c#

Does anyone know how to set the dropdownUI value with a string in unity?
I know how to set it up with an int like these
public DropDown dropdown;
dropdown.value = 1;
However, what I want is to set the value with a given string.
Something like:
dropdown.value = "an Option";

Look at the documentation of Dropdown.value:
public int value;
The Value is the index number of the current selection in the Dropdown. 0 is the first option in the Dropdown, 1 is the second, and so on.
it is of type int so in short: you can't
You could however get the index from the available options itself using IndexOf:
// returns a list of the text properties of the options
var listAvailableStrings = dropdown.options.Select(option => option.text).ToList();
// returns the index of the given string
dropdown.value = listAvailableStrings.IndexOf("an Option");
you could do the same also in one line using FindIndex
dropdown.value = dropdown.options.FindIndex(option => option.text == "an Option");

We can't add string value to the dropdown value field. So if you need to show an option having the given string then use FindIndex option to find that option in the dropdown and then assign that index to the value field.
dropdown.value = dropdown.options.FindIndex(option => option.text == "an Option");

This answer was written under the assumption you wanted to set the text of a dropdown item. As setting the value as a string is impossible, since the value is of type int. See derHugo's answer for how you can get the index from an option.
dropdown.value does not actually represent the text is shows. instead value
is the index number of the current selection in the Dropdown. 0 is the
first option in the Dropdown, 1 is the second, and so on.
As described in the docs here
What you are looking for is Dropdown.itemText (docs)
Meaning to set the text in your dropdown item you'll have to do the following: dropdown.itemText = "an Option";
A more complete guide on how dropdown menu's work can be found in the Unity manual here

Related

How to sort a numeric set of strings that are added to a combobox? C#

I want to display in ascendent order a list of string (numbers) that is added to a combobox. The project is in .NET 4.7.2
I have a string list of numbers such as:
{"3.453","1.123","2.024","1.567"}
and I would like that when these are displayed in my combobox they appear in order :
{,"1.123","1.567","2.024","3.453"}
The values come from reading multiple XML files and when the name == CardID is found it is added to the combobox "cb_card" items.
...
if (name == "CardID")
{
if (!mainWindow.cb_card.Items.Contains(value))
{
mainWindow.cb_card.Items.Add(value);
}
}
...
I have tried to:
Set the Combobox property Sorted = "true" but an error appears:
XLS0413 The property 'Sorted' was not found in type 'ComboBox'.
I tried to add the values to a list, then sort the list and finally add them to the combobox. I edited the code shown above:
...
List<string> sortedCardId = new List<string>();
if (name == "CardID")
{
if (!mainWindow.cb_card.Items.Contains(value))
{
sortedCardId.Add();
}
}
sortedCardId.Sort();
foreach (string ID in sortedCardId)
{
mainWindow.cb_card.Items.Add(ID);
}
...
but the order stayed the same as when it is nor ordered.
I tried some variants of this last code, by converting the string list in doubled, sort it and reconvert it ot string, but I got to many errors qhich I couldn't debugg with my current knowledge.
I tried to add the values to an array instad of a list, sort the array and add the values, but then the combobox appeared empty.
thanks a lot for your time and help in advance .
You can use List.Sort for this. If you are sure that the list contains only numeric values that can be parsed as a decimal (or double, ...), you can use a custom sort comparison that converts the strings to a decimal before comparing them:
var lst = new List<string>() {"3.453","1.123","2.024","1.567"};
lst.Sort((string a, string b) => (int)(decimal.Parse(a) - decimal.Parse(b)));
// This writes the list content as "1.123, 2.024, 1.567, 3.453"
Console.WriteLine(string.Join(", ", lst));
When comparing two items, the comparison returns
less than 0: a is smaller than b
0: a == b
greater than 0: a is bigger than b
This is why subtracting b from a leads to a correct result of the comparison.

What is a good way to set a default value in a sorted ComboBox?

When I initialize a combobox with text contents like so, where eo is some object with a ToString() override:
foreach (EncodingInfo ei in Encoding.GetEncodings()) {
Encoding e = ei.GetEncoding();
encodeObject eo = new encodeObject();
eo.Name = ei.DisplayName;
eo.Value = ei.Name;
int targetIndex = this.targetEncodingBox.Items.Add(eo);
}
I can set this to be the default value by using
this.targetEncodingBox.SelectedIndex = targetIndex
However, when the box is actually sorted, and the data initially entered into the box using the Add() method is not sorted, the default index is kept while the box is re-sorted, resulting in an entirely different value being selected almost all of the time.
A basic solution for this is to look up the generated value that the combobox would display and use FindStringExact:
this.targetEncodingBox.SelectedIndex = this.targetEncodingBox.FindStringExact("utf-8 -- Unicode (utf-8)");
However, this results in other problems. The string in question may depend on the user's operating system' language settings in this particular case. This can't be known beforehand.
Thus another way I've found is to manually find the name of the encoding a second time and set the SelectedIndex after the box is fully populated, using the same convention for concatenating the acronym name and translated name as used in the definition for encodeObject.ToString();.
foreach (EncodingInfo ei in Encoding.GetEncodings()) {
if (ei.Name == "utf-8") {
this.sourceEncodingBox.SelectedIndex = this.sourceEncodingBox.FindStringExact(ei.Name + " -- " + ei.DisplayName);
}
}
Note: the definition of the class encodeObject below:
private class encodeObject {
public string Name;
public string Value;
public override string ToString() {
return Value + " -- " + Name;
}
}
This actually works, and does exactly what I want, yet the solution seems quite clunky to do something that should really be a single call. Is there a better way of achieving this?
As Hans commented you need to create that list and store it to a variable.
Since the available encodings are unlikely to change anyway, this should happen in some class constructor or when you load your settings.
This variable then can be re-used anywhere you need it, it also can be easily updated & sorted as you like.
After this step the rest is trivial, create a variable with a default value/index, and once a ComboBox was assigned this list just set the SelectedValue/SelectedIndex value to your default value/index.

if ListBox.SelectedIndex contains a number 1

Basically i'm trying to make it so if the Selected Index from a listbox (for example lets say the selected index is "Server1") contains a number ("1") or a certain word ("Server") it would do a certain thing. For example: If the selected index from the listbox contains a number 1, it would enter 1 into a text box. If the selected index contains a number 2, it would open up a application, just for an example.
what i tried:
if (csrListBox.SelectedIndex = "1");
and:
{
List<string> items = ListBox.Items.Cast<string>().ToList();
foreach (string item in ListBox.Items)
{
Regex regex = new Regex(#"1");
Match match = regex.Match(item);
if (match.Success)
{
*Doing Something*
}
}
ListBox.DataSource = items;
}
Try this:
if (csrListBox.SelectedIndex == 1);
The second "=" sign matters - it states you're doing a boolean check instead of assigning value "1" to the value.
Mistake - You are assigning value.
Use compare operator ==. and SelectedIndex is int not string.
if (csrListBox.SelectedIndex == 1)
{
// Your code goes here.
}
I would suggest you work with ListBox item values instead of selectedIndex as the SelectedIndex can only be an integer value. Something like this linq query will return if the ListBox contains a certain value that is selected. This takes care of multi-selections too.
var myValue = "1";
bool listContainsItem = ListBox.Items.Any(item => item.Value == myValue && item.Selected);

How to get the previous value in a list of strings in c#?

I'm trying to implement a previous and next buttons.
I have a list of string called list1 which is filled with whatever is a user has inputted from a textbox. I can't access the previous (not the last) string in the list. IndexOf method isn't useful as I don't know what user will input.
private void previousBtn_click(object sender, EventArgs e)
{
getList();
int min = 0;
int max = list1.Count;
if(max==min)
{
previousBtn.Visible = false;
}
else
{
int temp =list.Count-1;
//how do I get my string if I know the element index from the previous line?
//textbox1.Text = thatPreviousString;
}
}
Sorry, it should be easy but I can't figure it out. How can I actully get my previous string in the list if the value is kind of unknown to me, so I can't just use find() and indexOf.
MSDN shows that there is a property called Item but there is no proper tutorial or code bit that shows how to use it.
UPDATE:
Let's say the user has typed "www.google.com", "www.facebook.com", "twitter.com" and then "www.yahoo.com". This urls are saved in list1. The last one was "www.yahoo.com", I can get it by calling Last(). The user can press the previous button anytime, so I can't specify the number of elements in list1, it's growing dynamically. I can only get the number of elements by calling
list1.Count and the last index by calling list1[list1.Count-1]
Now I know the number of indexes and elements, so how do I get the previous string, e.g. "www.twitter.com", if I can only say I can give you the index, give my string back?
By the way, ElementAs is only for arrays, doesn't work for lists.
how do I get my string if I know the element index from the previous line?
int prevIndex; // element index from the previous line that you know
string temp = list1[prevIndex - 1];
string temp =list[list.Count-1]; will give you the last element in the list.
string temp =list[list.Count-2]; will give you the previous element.
Remember, lists are 0-indexed, ie the first element is accessed via [0], so the last element will be [list size - 1].
So in your case textbox1.Text = list[list.Count-2]; will write the previous string into the textbox.
However, that won't give you a proper previous functionality. Pressing previous again won't give you list[list.Count-3]. You could though have a currentIndex variable that you decrement whenever previous is pressed for example and do textbox1.Text = list[currentIndex].

Check for specific value in a combobox

How can I check that a combobox in winforms contains some value?
Is there any way of doing it without iterating through all items?
if (comboBox1.Items.Contains("some value"))
{
}
If the items are some custom object instead of strings you might need to override the Equals method.
int index = comboBox1.FindString("some value");
comboBox1.SelectedIndex = index;
http://msdn.microsoft.com/en-us/library/wxyt1t12.aspx#Y500
There's also FindStringExact http://msdn.microsoft.com/en-us/library/c440x2eb.aspx
The other answers didn't work for me.
This did:
if (comboBox1.Items.Cast<string>().Any(i => i == position))
{
// Items contains value
}
Hope this helps!
To find exact data from combo box we have to check with FindStringExact
int resultIndex = cbEmployee1.FindStringExact(item.Text);
Using the accepted answer did not work for me as it always returned false even though a check of the list show the value present. What I use is the FindStringExact method, as recommend by Louis and Amit. In this case its a value entered in the comboBox text box.
var index = comboBox1.FindStringExact(comboBox1.Text)
if(index > -1)
{
//Success followup code
}

Categories

Resources