简体   繁体   English

如何获取选定值的ID?

[英]How to get the Id of the selectedvalue?

I have DropDownList with the following values: 我的DropDownList具有以下值:

ddl.SelectedValue = { Id = 234, Name = "ABC Name" }

How can I get the value of the Id? 如何获得ID的值?

I use WinForms and RadDropDownList 我使用WinForms和RadDropDownList

Try this one: 试试这个:

public int GetId(object obj)
{
    var anon = new { Id = 0, Name = string.Empty };
    var obj2 = MakeSameType(obj, anon);
    return obj2.Id;
}

public static T MakeSameType<T>(object obj, T anonymous)
{
    return (T)obj;
}

use it like: 像这样使用它:

int id = GetId(ddl.SelectedValue);

If it works, it is thanks to how the equivalent anonymous types are "condensed" in single types by the C# compiler. 如果可行,这要感谢C#编译器将等效匿名类型“压缩”为单个类型。

Note that this solution is as brittle as you can have 请注意,此解决方案非常脆弱

If you add/remove/rename a property of the anonymous type, the GetId will break (you'll have to keep the var anon = new {...} perfectly aligned). 如果添加/删除/重命名匿名类型的属性,则GetId将中断(您必须使var anon = new {...} 完全对齐)。 If you move the method that creates the collection of anonymous types to another assembly it will break too (because only anonymous types inside the same assembly are "unified" by the compiler). 如果将创建匿名类型集合的方法移至另一个程序集,该方法也将中断(因为只有同一程序集中的匿名类型被编译器“统一”)。

In general you shouldn't have anonymous types that "escape" a method. 通常,您不应该具有“转义”方法的匿名类型。 An anonymous type should remain in the method that it is defined. 匿名类型应保留在定义的方法中。 Assigning it directly as the DataSource of a control is asking for problems. 直接将其分配为控件的DataSource遇到问题。

If you feel lazy and don't want to create a type for a key-value, use the Tuple : 如果您感到懒惰并且不想为键值创建类型,请使用Tuple

var tuple = Tuple.Create(something, somethingelse, somethingstillelse);
var value1 = tuple.Item1;
var value2 = tuple.Item2;
var value3 = tuple.Item3;

and so on. 等等。

As your are using anonymous types, it gets little complicated. 当您使用匿名类型时,它变得有点复杂。 But, you can cast SelectedValue to dynamic, and exstract 'Id' from there: 但是,您可以将SelectedValue强制转换为动态值,并从此处提取“ Id”:

dynamic selectedValue = ddl.SelectedValue;
int id = selectedValue.Id;

But i would recommend to declare your own class or struct for such cases. 但是我建议在这种情况下声明自己的类或结构。

I have changed the LINQ query 我已经更改了LINQ查询

from: 从:

var query = (from q in tableq where ...
             select new {Id = q.Id, Name = q.Name});

to: 至:

var query = (from q in tableq where ...
             select q);

... and then change it to: ...然后将其更改为:

table1.Id = (ddl.SelectedValue as tableq).Id == null ? table1.Id : (ddl.SelectedValue as tableq).Id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM