I have small form with one dropbox, one textBox, two ComboBoxes and one list(for selection).
Code has no errors, but when I attempt to save the form and store data in database I get this:
System.InvalidCastException: 'Unable to cast object of type
'Windows.UI.Xaml.Controls.ComboBoxItem' to type
'System.IConvertible'.'
+ $exception {System.InvalidCastException: Unable to cast object of type 'Windows.UI.Xaml.Controls.ComboBoxItem' to type 'System.IConvertible'.
at System.Convert.ToInt32(Object value)
Here is the code:
Db_Helper.InsertData(new
Data((Convert.ToString(listBox1.SelectedItem)),
(Convert.ToString(SelectedProductName.Text.Trim())),
(Convert.ToInt32(TextBox1.Text)),
//error below
(Convert.ToInt32(ComboBox1.SelectedItem)),
(Convert.ToString(ComboBox2.SelectedItem))));
I believe the problem is with ComboBox1 Conversion.
You do your conversion wrongly. 'Windows.UI.Xaml.Controls.ComboBoxItem' is a usual CLR Object as everything in the .NET. Each object ships overloadable .ToString() method, so whenever you want default string representations of whatever object or it's subclass, you rather call myObject.ToString().
Same applies to the ToInt32(...). Proceed on .int.Parse/TryParse to get strongly typed integer from the string. When you'll do this, you'll get a clearer error at least.
I think your casting syntax is wrong to convert into string we use toString method at the end of the statement like below.
ComboBox2.SelectedItem.toString();
I Hope This Will Help You
Or instead of SelectedItem use Text property of combobox like below
ComboBox2.Text
and you don't have to convert it into string it always returns string
I Hope This Will Help You
I got the solution myself.
The error was indeed at this line:
(Convert.ToInt32(ComboBox1.SelectedItem)),
I had to modify it a bit like this:
(int.Parse(ComboBox1.SelectedIndex.ToString())),
I was getting errors until I changed
SelectedItem
to
SelectedIndex
. Program works well now and I am able to pull selected data from ComboBox.
The SelectedItem property gives you the ComboBoxItem. What you want is only the value, so use the SelectedValue property instead.
You wanted to convert the value to an integer, but the Convert.ToInt32() takes a string while the SelectedValue property is an object. You can use the .ToString() on it to convert it to string.
Also don't convert string values (like SelectedProductName.Text) to string, that's redundant.
Db_Helper.InsertData(new
Data(listBox1.SelectedValue.ToString(),
SelectedProductName.Text.Trim(),
Convert.ToInt32(TextBox1.Text),
Convert.ToInt32(ComboBox1.SelectedValue.ToString()),
ComboBox2.SelectedValue.ToString());
EDIT You need to bind your ComboBoxes and ListBox properly using the DisplayMemberPath and SelectedValuePath properties. The first one will display the items' text, and the second one will store the items' ID. Then you can get the ID using the SelectedValue property in the code above.
Here is an example of how to bind the ComboBox to a list of vegetables sorted alphabetically:
var data = new Dictionary<int, string>{
{100, "Eggplant"},
{102, "Onion"},
{300, "Potato"},
{105, "Tomato"},
{200, "Zuccini"}
};
ComboBox1.ItemsSource = data;
ComboBox1.DisplayMemberPath = "Value";
ComboBox1.SelectedValuePath = "Key";
Your ComboBox1 in XAML must have no items. As you can see, I bound the DisplayMemberPath to the Value of the Dictionary and the SelectedValuePath to the Key. You can use any values you want for IDs and they don't have to be sequential like the index. This way, if you add a new item in the future, the IDs of the current items will not change. Let say you want to add Garlic in the alphabetical order:
var data = new Dictionary<int,string>{
{100, "Eggplant"},
{302, "Garlic"},
{102, "Onion"},
{300, "Potato"},
{105, "Tomato"},
{200, "Zuccini"}
};
If you use int for the Key, you don't need to convert it like you did in your code, you can simply use a direct cast. Similarly, for listBox1 and ComboBox2 you can use string for the Key if you like and you won't need conversion:
Db_Helper.InsertData(new
Data((string)listBox1.SelectedValue,
SelectedProductName.Text.Trim(),
Convert.ToInt32(TextBox1.Text),
(int)ComboBox1.SelectedValue),
(string)ComboBox2.SelectedValue);
If you prefer to keep the items in XAML instead of code-behind, there is no equivalent to the SelectedValuePath property, but you can simulate it using the Tag property like this:
<ComboBox x:Name="ComboBox1" SelectedValuePath="Tag">
<ComboBoxItem Content="Eggplant" Tag="100" />
<ComboBoxItem Content="Onion" Tag="102" />
<ComboBoxItem Content="Potato" Tag="300" />
<ComboBoxItem Content="Tomato" Tag="105" />
<ComboBoxItem Content="Zuccini" Tag="200" />
</ComboBox>
Related
I'm having problems with a datagridview. I'm trying to export the row selection of datagridview1 in a array to be used in a chart in the same solution. I need to convert those id's to the actual collection name. I tried with a enum list to convert the id to the collection name, but compiler gives me a error so in the end I used a case switch. Is enum the correct way to go to convert an id to a collection name or should I follow a different road?
e.Graphics.DrawLine(Pen, position1, position2(Enum.GetName(typeof(collectioname),idofcollectioname), positionx2, positiony2));
I am not sure if I got your question but,
I need to convert those id's to the actual collection name
If you mean by Id some value that can be one of Limited Set of values, the answer is YES, you can use an Enum.
But if the Id something else, the answer is NO, you can't use it.
I am trying to work out how to multiply a selected value in a ComboBox by a string value stored in a label. I have tried converting both values to ints but this error keeps appearing:
Unable to cast object of type 'System.Windows.Controls.ComboBoxItem' to type 'System.IConvertible'.
int quantity = Convert.ToInt32(comboBox3.SelectedItem);
int price = Convert.ToInt32(label1.Content);
label2.Content = quantity*price;
Many Thanks
I don't quite remember which exact property of ComboBoxItem it was (I think Text), but you need to get the value of its string rather than the whole object to perform the conversion. After that, just use int's ParseString class method.
You want the SelectedItem's Content, not the SelectedItem itself (assuming WPF):
Convert.ToInt32(comboBox3.SelectedItem.Content);
But if you have set SelectedValuePath and are using some data binding to a model, you can get the selected value in an easier way (without even using convert, if the model is an integer):
comboBox3.SelectedValue
Hi I have windows form with a Combo filled with 3 options where their values are Guid's and that has a DataBinding to a selected object.
EmployerMemberDefault item = EmployerMemberDefault();
item.GroupUid = Guid.Empty;
cbGroupEmployer.DataBindings.Clear();
cbGroupEmployer.DataBindings.Add("Value", item, "GroupUid");
When I create a new object the property that is databinded to the combo is set to Guid.Empty. If I compile and run, when I create that new object I see "00000000-0000-0000-0000-000000000000" in the combo. Is there any way I can see empty text in the combo instead of the Guid.Empty value?
Thanks.
Change the source property from Guid to Guid?/Nullable<Guid> I haven't done this with Guid, but it works with int/DateTime and other types that do not allow null.
"00000000-0000-0000-0000-000000000000" is what Guid.ToString returns. To show something different you'd have to translate that value in some way--i.e. bind to something else that stores the guid and translates it.
During the construction of user control I populate the combobox with some data. Works fine. I have Status.ID as valuePath and Status.Name as displayPath.
cmb.ItemsSource = dbEntities.Status
The comobox will be used as a filter control and I need to insert some value for "All", which will be used as the empty filter.
First I tried a funny solution:
ObjectSet objectSet= dbEntities.Status;
Status stAll = new Status();
stAll.ID = -1;
stAll.Name = "All";
objectSet.AddObject(stAll);
cmb.ItemsSource = objectSet;
For some reason the object is not added to the objectSet. It didnt throw any exception either.
Then I tried to insert it manually to the first index but I got the error:
"Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."
My code looked like:
cmb.ItemsSource = entities.Status;
cmb.Items.Insert(0,"All");
Both didnt work. What would be the easiest way to add that line to the combobox? The error message got me confused. I am not sure how to use the ItemsSource for such a purpose.
edit: I did not have enough rep to answer my own question so here is the working code. Thanks Craig again.
CompositeCollection comp = new CompositeCollection();
comp.Add(new CollectionContainer {Collection = dbEntities.Status});
Status stAll = new Status();
stAll.ID = -1;
stAll.Name = "All";
comp.add(stAll);
cmb.ItemsSource = comp;
//do whatever filter you want when the selected value is -1
There are a couple different problems with what you are trying to do. You can't manipulate the Items when you are using the ItemsSource, instead you have to go through the object that is set to the ItemsSource. That is what the error message is about in the second part. Its because when you set the ItemsSource the Items value is unused it is not populated with the values of the ItemsSource.
I'm not familiar enough with the ObjectSet class to know why the first case is not working. However, it seems awkward to add an item to your values you are pulling from somewhere else, just to have the all case. The better solution is to use a null value to represent nothing. Unfortunately, there is no built in way to do this in WPF. However, there is a fairly easy solution of using an Adaptor do do this. I have used this solution a NullItemSelectorAdaptor, that enables null as a selection even if null is not in the list. All you have to do is wrap your combobox in the NullItemSelectorAdapter and null will be added as a value. The blog post explains everything pretty clearly, so I won't repeat it. You than can setup your filter so that null equates to no filtering.
How to insert a Combobox value in to a database. When i hit Save button in my application, it will stored stored into database like this way..
System.Windows.Controls.ComboBoxItem
What i do for getting correct value of a combo box?
if you are using a string in the combobox, then you can use the example that Akash Kava showed.
Also, if the combobox contains other elements, you can get those elements through the use of something like
((ComboBoxItem)rpcombo.SelectedItem).Content.ToString()
and casting it to what you need.
lets say your combobox has string items what you need is like this
froeach( ComboBoxItem item in ComboBox1.Items )
{
string str = (str)item;
// saving value
}
Best Regards,
Iordan
This question seems a bit too broad. We are going to need nore information about this to be able to answer this one.
What kind of database are you using?
Are you connected to the database or do you need help with tahat as well?
In that case there are alot of good reading on the internet to your aid, that I can link to.
Do you want to save the ComboBoxItem as an .net object or det values of the item?
The list can go on, you have to give me something more to chew on.
MyObject obj = myComboBox.SelectedItem as MyObject;
obj.ValueIamInterestedIn; <--- this should be inserted
or if you have string or any valuetype array as ItemsSource then,
myComboBox.SelectedItem.ToString();