How to bind enums to dropdown list? - c#

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?

Related

Get Values from anonymous type

In one button I made a query where I selected these 3 values: idStudent, name, lastName and bounded to a DataGridView and now I get those values again to use them in another button with this:
var Selected = dgvShow.CurrentRow.DataBoundItem;
And the result from Selected is this:
{idStudent = 31, name = "John", lastName = "Travolta"}
The above result is an Anonymous Type, so how can I get those values and show them in a TextBox?
Also:
Can I get a single value from that var ("Selected")?
Is it possible or I have to change my code?
PS: I'm using Entity Framework, C#
To use your properties as an anonymous type you can cast it to a dynamic.
Eg:
var Selected = dgvShow.CurrentRow.DataBoundItem;
var objDynamic = (dynamic)Selected;
Console.WriteLine(objDynamic.idStudent);
I would recommend using a model instead of an anonymous type and unbox your DataBoundItem into your model, it will benefit accessibility of your property names via IntelliSense and make it more manageable for other people to maintain.

Anonymous type dynamic object error cant implicitly convert string to int

In order to make sortable an asp grid bound to an linq result set at runtime with dynamic fields (so I can't create template fields) I decided to try serializing the table's results and putting it in a viewstate to be called, de serialized, ordered and rebound on the gridview's sorting event.
Unfortunately the assigning to a new type after the fact gives the error Cannot implicitly convert type 'string' to 'int', but I cant work out why/where it would be trying to do this.
The code up to the point of failure is:
string sSData = (string)ViewState["resultData"];
JavaScriptSerializer jSS = new JavaScriptSerializer();
dynamic dynObject = jSS.DeserializeObject(sSData);
var resultsdDS = new
{
Student_Forename = dynObject["Student_Forename"],
Student_Surname = dynObject["Student_Surname"]
};
There is the correct datatypes in the dynObject (some are ints), but not in the selected fields though the error indicates its trying to turn a string to an int, not vice versa (and these fields arent assigned anyway in this test)
Anything to help me understand what's going on would be appreciated!

How To Move Row In DataBound DataGrid In C# without Knowing The Object Type

I have a number of datgridgs that I want to be able to reorder rows for. They are all SortableBindingList<> : List<> types but they contain different objects. I tried casting the DataGridView's DataSource to SortableBindingList<object> to .RemoveAt() & .Insert() but the cast failed. I tried to pass the object type into the function using a Type but that failed.
Type objType;
...
var x = (SortableBindingList<objType>) dataGridView.DataSource;
but that doesn't work either, nether does 'typeof(objType)`.
Not sure how to proceed.
Turns out that I can do this with dynamic types.
dynamic list = dgv.DataSource;
var item = list[rowIndexFromMouseDown];
list.RemoveAt(rowIndexFromMouseDown);
if (rowIndexOfItemUnderMouseToDrop == -1)
list.Add(item);
else list.Insert(rowIndexOfItemUnderMouseToDrop, item);

Adding enum to combobox

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.

Convert object to enum C#

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());

Categories

Resources