I have binded a list of enum to a combobox. Now I want to get the SelectedItem return the enum, which currently returns it as type object. How do I convert this object to my enum?
My framework is silverlight on windows-phone-7
Cast it directly:
MyEnum selected = (MyEnum)cboCombo.SelectedItem;
Note that you can't use the as cast in this case since an Enum is a value type.
Have you tried this??
YourEnum abc = (YourEnum) Enum.Parse(typeof(YourEnum), yourObject.ToString());
Related
For example:I have 2 variable (value ) & (property) i want to check is cast possible for value? We do not know the type of variables, How to check if cast is possible?
var value = Reader[item];
PropertyInfo property = properties.Where(x => x.Name == item).FirstOrDefault();
var type=property.PropertyType;//Or property.ReflectedType
var cs= value as type // Error: type is variable but is used like a Type
if (cs!=null){
...
}
Sample 1:
var value = 123;//is int
type = property.GetType();// is double
var x = (double)value;//Can be casted
Sample 2:
var value = "asd";//is string
type = property.GetType();// is double
var x = (double)value;//Can not be casted
You can use IsAssignable:
bool isValidCast = type.IsAssignableFrom(value.GetType())
As per the comments about int to double:
I've made a mistake in my comment, so i deleted it.
int can be implicitly converted to double because there is a predefined implicit conversion, see here
There are many ways to convert or cast from type to type. For example, You can use implicit/explicit conversion, you can use TypeConverter or implement the IConvertible interface.
Now, you have to decide which use case is relevant to you. It can be a bit complex to check them all, especially without knowing the destination type at design time.
In your code snippet, type is a variable of type Type, hence why it is throwing that error. You can change your code to use Convert.ChangeType() instead. Something like this:
var value = Reader[item];
PropertyInfo property = properties.Where(x => x.Name == item).FirstOrDefault();
var type=property.PropertyType;
object cs= Convert.ChangeType(value, type);
if (cs!=null){
...
}
Notice that, since you don't know the strong type of your property at compile time, you still have to box it into an object type after changing its type. This means you wouldn't be able to access its properties and methods directly using dot syntax in code (e.g. cs.MyProperty). If you wish to be able to do that, you can use the dynamic type in C#:
dynamic dcs = cs;
Console.Write(dcs.MyProperty);
When using Convert.ChangeType() you have to make sure you are converting to the correct type. E.g.:
if (value.GetType() == type)
{
object cs= Convert.ChangeType(value, type);
}
I used linq to get a set of Enums except one.This is my Linq
List<SyncRequestTypeEnum> lstDefaultSyncList = (List<SyncRequestTypeEnum>)(Enum
.GetValues(typeof(SyncRequestTypeEnum))
.Cast<SyncRequestTypeEnum>()
.Except(new SyncRequestTypeEnum[] { SyncRequestTypeEnum.ProjectLevel })).ToList();
SyncRequestTypeEnum is my enum class which has 3 Enums.
Here I am using (Enum.GetValues(typeof(SyncRequestTypeEnum)) so I am getting values. Now I am binding these values to dropdownlist as:
((DropDownList)control).DataSource = HtmlEncodeHelper.HtmlEncode(lstDefaultSyncList );
((DropDownList)control).DataBind();
This is not binding the actual enums. In UI it is displaying the values as System.Data.DataRowView. If I use GetNames instead of GetValues it is throwing a cast error
can someone help on this?
I have the following drop down in my aspx:
<aspx:DropDownList
ID="ddl1"
runat="server"/>
In the code-behind (C#), I want to retrieve the value from the DropDownList.
I populated my dropdown as such:
ddl1.DataSource = LocationOfData;
ddl1.DataBind();
LocationOfData returns of type CustomType. EDIT: CustomType is an enum.
I want to be able to accomplish the following:
CustomType? myvar = ddl1.Text
In other words, create a nullable variable using my CustomType and set it equal to the variable from the drop down. But the type that I can only retrieve Text (String) from ddl1.
If CustomType is an Enum you first have to parse your ddl1.Text to an Enum and then cast it to a Nullable type:
CustomType? myvar = (CustomType?) Enum.Parse(typeof(CustomType), ddl1.Text, true)
If CustomType is an enum, instead of binding the name of the enum, I would set the values of your drop down list when you bind to the byte value of the enum. Then when you are attempting to cast to CustomType, you can just do:
CustomType myvar = (CustomType)byte.Parse(ddl1.Text);
Do a check first to create a nullable type. I don't know what your criteria is, but:
CustomType? myvar;
if(/*Criteria*/)
{
myvar = (CustomType)byte.Parse(ddl1.Text);
}
else
{
myvar = null;
}
Right now, to be sure I am getting what I want I am using
actionComboBox.Items[actionComboBox.SelectedIndex].ToString()
to retrieve the string that is stored as an item in my TextBox
Does one of the Selected properties return my above statement? I can never seem to get what I want when I use those.
Like, does actionComboBox.SelectedItem as string return the above value?
EDIT:
I guess the true question here is: What do each Selected Property return such as; SelectedItem, SelectedValue, SelectedText.
I think SelectedText returns the text that is selected if you are able to edit the text in the combo box. I don't think you use this property if you have the DropDownList style selected where the user cannot just type values into the combobox.
SelectedValue only applies if you are bind to a datasource. SelectedValue will return the item in the datasource you've selected, or if you have the DisplayMember field filled in, the value of the property/column that you have specified.
SelectedItem will return the selected item if you have just filled in the list items through the designer.
I get burned on these all the time, cause I always forget. The big question in your example is how are the items being populated into the combo box, that will affect the return values of these properties.
ComboBox.Items is a collection of System.Object's, so it can be anything. By default the ComboBox displays the return value of an object's ToString method. Whatever you add to the ComboBox will be what you will get back, though its returned as a System.Object and you will have to convert it back to its original type to access its members.
comboBox.Items.Add("foo");
The above will add a System.String to the ComboBox.
class Foo
{
public String Bar { get; set; }
}
Foo foo = new Foo();
foo.Bar = "Value";
comboBox.Items.Add(foo);
The above will add a Foo to the ComboBox. So to get your values back.
Object obj = comboBox.Items[comboBox.SelectedIndex];
Foo foo = obj as Foo;
if (foo != null) { // check just in case
}
For strings, there's no need for a conversion, calling ToString is fine. It's better to just use SelectedItem instead.
Foo foo = comboBox.SelectedItem as Foo;
if (foo != null) { // again, check to make sure
}
The power of the ComboBox is that since it stores a collection of System.Object, you can store multiple types of objects, but you are in charge of converting it back to whatever usable type it was to begin with when you need to access it.
Hi may i know how to get the enum value below to bind into the combobox?
I wrote the below code which works well but wonder is this the best way.
public enum CourseStudentStatus
{
Active = 1,
Completed = 2,
TempStopped = 3,
Stopped = 4,
}
//Bind Course Status
Dictionary<string, int> list = new Dictionary<string, int>();
foreach (int enumValue in Enum.GetValues(typeof(CourseStudentStatus)))
list.Add(Enum.GetName(typeof(CourseStudentStatus), enumValue), enumValue);
var column = ((DataGridViewComboBoxColumn)dgv.Columns["studentCourseStatus"]);
column.DataPropertyName = "StudentStatus";
column.DisplayMember = "Key";
column.ValueMember = "Value";
column.DataSource= list.ToList();
----------------- UPDATE -------------------
Hi i have changed my code to this according to Sanjeevakumar Hiremat and it works perfectly.
cbStatus.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
However, when i want to a Get() and want to bind the value back to the cbStatus, it cast error {"Object reference not set to an instance of an object."}
cbStatus.SelectedValue = Course.Status;.
The cbStatus.Datasource is not empty and it has value after bound to cbStatus.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
please advice.
Following should be the simplest way to bind it.
column.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
To get the selected value you need to cast it to the enum type.
CourseStudentStatus selectedValue = (CourseStudentStatus)column.SelectedValue
Enum.GetValues returns an array of the enumType values which can then be bound to any control.
I've tested this on a standalone combobox, not in a combobox column in DataGridView, YMMV.
I don't think there is a best way. I used to do something similar with a GenericListItem<T> class where T is the backing value, in your case, an enum.
This class exposed Display string and Value T properties to bind to. I think I was also overriding ToString because it is the default if you don't specify the DisplayMember. I went further and made a constructor taking just Value and defaulting Display to Value.ToString, which in the case of enums works I think.
I'd then make a List<GenericListItem<T>>, feed that into the DataSource of the column and set the DisplayMember and ValueMember properties accordingly in code. This list is the alternative to the dictionary used in your example.
But I'm not saying it's a better solution :-) however it means you can remove code, say enum iteration, into this class or specialise the class for handling certain data types better, all with the end goal of being inserted into a list and bound to a control.