I'm doing a project where "ToString" is being used as a method.
private void button1_Click(object sender, EventArgs e)
{
if(cboPlaneType.SelectedItem = "Generic")
{
}
else if (cboPlaneType.SelectedIndex = "Passenger")
{
}
else if (cboPlaneType.SelectedIndex = "Fighter Jet")
{
}
}
And in this case i'm not sure what to do. As you can see I've tried a few different option but with no avail. I've also tried
if((string)cboPlaneType.SelectedItem = "Generic")
And that didn't work.
**Edit
Just to point out, SelectedValue wasn't the correct answer.
ended up being "if((string)combobox.SelectedItem == "Generic")
The equality operator in c# is ==; = is an assignment operator.
SelectedIndex will return an int representing the zero-based position of the item that is selected. (I'm guessing it returns -1 when no item is selected.)
SelectedItem can be an object of any type; if it is not a string then you can't match it by comparing with a string.
Are you saying that the objects with which the ComboBox is populated override ToString()? You should still be able to use the result of that method for comparison, because it can only return a string. Otherwise, you might be able to use SelectedValue, but this depends on what kind of ComboBox you are using and how you have set it up.
SelectedIndex is an property of type Int32.
Maybe you want to use SelectedValue instead ?
Related
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.
My code goes like this for simple practise problem which i am trying to build. I come across
Invalid Cast Exception. Specified Cast is not valid.
public Form1()
{
Combobox1.Datasource = foo.bar.dataset.tables[0];
Combobox1.DisplayMember = "Name";
Combobox1.ValueMember = "ID";
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
NewClass P2 = new NewClass;
P2.Filter.Id = (long)Combobox1.SelectedValue;
}
Can anyone tell me why is this happening and how to go about solving it even though I have typecasted Combobox1.SelectedValue object?
Maybe this will help:
P2.Filter.Id = Convert.ToInt64(Combobox1.SelectedValue);
According to your comment this might help:
P2.Filter.Id = Convert.ToInt64((Combobox1.SelectedValue as DataRowView).Item[0]);
I'm not sure why this happens, maybe someone can help me on that but I would prefer going.
P2.Filter.Id = Convert.ToInt64(Combobox1.SelectedValue);
That always works for me when I have this issue.
ComboBox.SelectedValue is obviously not a long. You should do whatever is required to change its type; most probably this would be
P2.Filter.Id = Convert.ToInt64(ComboBox1.SelectedValue);
Check the object reference before you cast SelectedValue.
long value=0l;
if (comboBox1.SelectedValue != null)
{
value=long.Parse(comboBox1.SelectedValue.ToString());
}
You can use SelectedItem property which will returns the reference of DataRowView (row).
DataRowView row = comboBox1.SelectedItem as DataRowView ;
if (row != null){
MessageBox.Show("value " + row[0] + " " + row[1]);
}
Casting a string to long is mal-casting. SelectedValue is supposed to return a string that needs Convert.ToLong to operate on
Convert.ToInt64(Combobox1.SelectedValue)
Rather try something like
Convert.ToInt64
Converts a specified value to a 64-bit signed integer.
At some later stage you might also want to take a look at using
Int64.TryParse Method
Converts the string representation of a number to its 64-bit signed
integer equivalent. A return value indicates whether the conversion
succeeded or failed.
or Int64.Parse Method
Converts the string representation of a number to its 64-bit signed
integer equivalent.
Thickness t = new Thickness(0);
if (value != null)
{
t= new Thickness(System.Convert.ToInt64(((System.Windows.Controls.ComboBoxItem)value).GetValue(System.Windows.Controls.ComboBoxItem.ContentProperty)));
}
return t;
listBox2 contents:
0:FirstProduct
1:ProductAgain
2:AnotherProduct
3:OkFinalProduct
What I'm trying to do, when the selected index has changed on listBox2, is to have it make my int "DBID" the value of the number before the ":".
Here's my attempt:
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox2.SelectedIndex == -1)
{
return;
}
int DBID;
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(":"[0]));
ShowProduct(DBID);
}
ANY help with this is greatly appreciated :)
Thanks guys
EDIT -
Sorry, yes I actually tried:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
but im getting the following errors:
The best overloaded method match for string.Split(params char[])' has some invalid arguments
Argument1: cannot convert from 'string' to 'char[]
EDIT #2 -
When using:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
After running the application and clicking on a different listbox item, I'm encountering this exception:
NullReferenceException was unhandled. Object reference not set to an instance of an object.
I appreciate all the help so far guys!
Try changing:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(":"[0]));
To:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
Update
Try this instead. It explicitly adds a new char:
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(new char[] { ':' })[0]);
DBID = Convert.ToInt32(listBox3.SelectedValue.ToString().Split(':')[0]);
A safer way will be to replace the single statement with the following code,
if (listBox3.SelectedValue != null)
{
string selectedValue = listBox3.SelectedValue.ToString();
if (!string.IsNullOrEmpty(selectedValue))
{
if (Int32.TryParse(selectedValue.Split(':')[0], NumberStyles.Integer, CultureInfo.CurrentCulture, out DBID))
{
// Process DBID
}
else
{
// Cannot convert to Int32
}
}
}
Then use breakpoints in the code, to find where the NullReferenceException is occurring.
Note that this example assumes that you are using System.Windows.Controls.ListBox or System.Windows.Forms.ListBox, and not System.Web.UI.WebControls.ListBox. In the later case, the SelectedValue is a string and not an object (as pointed out by #Srinivas Reddy Thatiparthy in another answer's comment)
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
}
I am using:
if (RadioButtonList_VolunteerType.SelectedItem != null)
or how about:
if (RadioButtonList_VolunteerType.Index >= 0)
or how about (per Andrew Hare's answer):
if (RadioButtonList_VolunteerType.Index > -1)
To those who may read this question, the following is not a valid method. As Keltex pointed out, the selected value could be an empty string.
if (string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue))
Those are all valid and perfectly legitimate ways of checking for a selected value. Personally I find
RadioButtonList_VolunteerType.SelectedIndex > -1
to be the clearest.
In terms of readability they all lack something for me. This seems like a good candidate for an extension method.
public static class MyExtenstionMethods
{
public static bool HasSelectedValue(this RadioButtonList list)
{
return list.SelectedItem != null;
}
}
...
if (RadioButtonList_VolunteerType.HasSelectedValue)
{
// do stuff
}
The question revolves more around whether to check for null or check value of an int. Martin's great extension method could also be written:
public static bool HasSelectedValue(this ListControl list)
{
return list.SelectedIndex >= 0;
}
The MSDN documentation for a ListControl states:
Default for SelectedItem is null.
Default for SelectedIndex is -1.
So either are valid ways and both work. The question is which is the best way. I'm guessing SelectedIndex as it is a value type operation rather than reference type operation. But I don't have anything to back that up with.
I recommend:
RadioButtonList_VolunteerType.SelectedIndex>=0.
According to the Microsoft Documentation:
The lowest ordinal index of the selected items in the list. The default is -1, which indicates that nothing is selected.
string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue) will not always work as you can have a ListItem with an empty value:
<asp:ListItem Value=''>This item has no value</asp:ListItem>