我正在编写SharePoint应用程序。那里有下拉列表页面。我有
SelectedIndexChanged的处理程序。我想获取选定的值,但为CustomObject
,我看到的唯一选项是string
。我尝试过SelectedValue
,现在仍然是string
。
这就是我设置列表的方式:
protected void Page_Load(object sender, EventArgs e)
{
List<CustomObject> customList = //retrieving data
myDropDownList.DataSource = customList.Select(x => new { x.Name, Value = x});
myDropDownList.DataTextField = "Name";
myDropDownList.DataValueField = "Value";
myDropDownList.DataBind();
}
那是我尝试的方法之一:
protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
var index = groupingDropDownList.SelectedIndex;
CustomObject obj = (CustomObject)myDropDownList.Items[index].Value;
obj.DoSomething();
}
有可能吗?还是我必须在某处有对象的字典?
答案 0 :(得分:0)
您将需要利用html5数据属性,然后可以将其放在下拉选项中。这是您可以如何处理数据的示例。
// add Agencies' addresses as HTML5 data-attributes.
var agencies = agencyNames.ToList();
for (int i = 0; i < requesting_agency.Items.Count - 1; i++) {
requesting_agency.Items[i + 1].Attributes.Add("data-address",
agencies[i].address);
servicing_agency.Items[i + 1].Attributes.Add("data-address",
agencies[i].address);
}
然后,在处理信息时,您可以执行类似的操作。
var index = groupingDropDownList.SelectedIndex;
var selectedText = myDropDownList.Items[index].SelectedValue;
var selectedValue = myDropDownList.Items[index].Attributes["attribute"];
// put into obj
// do something with object
如果您有任何疑问,请告诉我。
答案 1 :(得分:0)
您要将对象(x => new { x.Name, Value = x})
绑定到下拉值,应将实际值绑定到该对象。
测试演示:
public class CustomObject
{
public int ID { get; set; }
public string Name { get; set; }
public CustomObject(int _ID,string _Name)
{
this.ID = _ID;
this.Name = _Name;
}
}
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<CustomObject> customList = new List<CustomObject>();
customList.Add(new CustomObject(1,"test1"));
customList.Add(new CustomObject(2,"test2"));
myDropDownList.DataSource = customList.Select(x => new { x.Name, Value = x.ID });
myDropDownList.DataTextField = "Name";
myDropDownList.DataValueField = "Value";
myDropDownList.DataBind();
}
}