Get Values from anonymous type - c#

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.

Related

How to get GridLookup with complex name

I'm trying to get GridLookup selected value,
#Html.DevExpress().GridLookup(settingsGrid =>
{
settingsGrid.Name = "CommandeDetailEnCours.Compte";
settingsGrid.KeyFieldName = "Numero";
[...]
}).BindList(Model.ListeComptes).Bind(Model.CommandeDetailEnCours.Compte).GetHtml()
The question is: How I can get Value because in javascript
"CommandeDetailEnCours.Compte".GetGridView() [...]
not work ?
Use the client-side GetValue method in the following manner.
To retrieve the complex name on the client use the How to use the ClientInstanceName and Name properties when they contain special characters approach.
var lookupClientInstance = ASPxClientControl.GetControlCollection().GetByName("CommandeDetailEnCours.Compte");
var value = lookupClientInstance.GetValue();
alert(value);

C# adding properties to already created dynamic object list

I am creating a list like following:
var result = data.Select(p => new
{
p.FirstName,
p.LastName,
Relationship = p.RelationshipType,
p.TierType,
Gender = p.GenderType,
p.AnnualSalary
});
However, I need to add more properties into each of the array item of result like following
foreach(var property in ListOfAdditionalProperties)
{
// Add property logic
}
Is this possible?
I tried ExpandoObject but was not able to come up with the final result list that I get with the Lambda mentioned on top.
No, it's not possible.
You cannot add more members to a dynamic type after the type has been created.
Think of it as a class declaration. Once the class is declared and compiled it cannot be modified.
You need to use another approach, just like the ones you mention. But yes, that has it's drawbacks in regards to syntax.

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!

Calling the property names of a dynamic property "ints": can't call property

I am assigning property names of a dynamic object as ints in string form. The int value represents an int ID in a database I am using. However I am stuck on how to retrieve the value assigned to the property as shown below:
dynamic test = new ExpandoObject()
IDictionary<string, object> proxyFiler = test as IDictionary<string, object>;
proxyFiler["four"] = 4;
proxyFiler["5"] = 5;
int r = test.four; // Works
int s = test.5; // Doesn't work
A method which reads the database will return an "int" and I would like to be able to access the property value with that property name.
To expand on this: what if I wanted to do a linq query to sort out a list of dynamic objects according to a property name? In this case I need to get the propertyName which I have retrieved as a string e.g. "15":
return disorderedList.OrderBy(o => o.propertyName).ToList();
Does anyone know a simple solution to this problem or do you recommend a different approach? Thanks.
In order for dynamic to work in this way, the key has to follow the rules for valid identifier names in C# (the rules are specified in this outdated MSDN page, but also in the C# language specification). A single number (5) is not an allowed identifier name, which is why that doesn't work.
Note that you can still retrieve the value by using the type as a dictionary, in a similar manner to how you populated it.
As for your second example - you are never using value, so it has no effect. It's the same as just writing int r = test.four;
Edit:
I believe, given your approach, you'd need to cast to a dictionary:
return disorderedList
.OrderBy(o => ((IDictionary<string, object>)o)[propertyName]).ToList();

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.

Categories

Resources