如何将方法绑定到dropdownlist
本文关键字:dropdownlist 绑定 方法 | 更新日期: 2023-09-27 18:21:46
我需要使用ASP.NET C#将一个方法绑定到DropDownList中。
我试过这个代码:
public DataTable gg()
{
DataTable _dt = new DataTable();
_dt.Columns.Add(new DataColumn("Name", typeof(string)));
DataRow dr = _dt.NewRow();
dr["Name"] = "jana";
_dt.Rows.Add(dr);
return _dt;
}
<asp:DropDownList ID="sd" DataSource='<%#Eval("gg()")%>' runat="server" />
它在DropDownList控件中没有显示任何内容。我的错误在哪里?
一种可能的解决方案是在Page_Load
事件中从代码后面绑定gg()
方法。首先,您的DropDownList控件不再需要数据源定义:
<asp:DropDownList ID="sd" runat="server" />
以及在Page_Load
事件中的代码隐藏页(*.cs)中:
protected void Page_Load(object sender, EventArgs e)
{
// specify the DataSource to use
sd.DataSource = gg();
// what field from the DataSource should be used for showing in the list
sd.DataTextField = "Name";
// what field from the DataSource should be used for saving (in this case the same)
sd.DataValueField = "Name";
// bind the control to the data source
sd.DataBind();
}
可以在MSDN BaseDataBoundControl中找到一个示例。
如果只想使用ASP.NET控件,则可以在aspx页面的某个位置定义ObjectDataSource对象(例如,就在关闭body标记之前):
<asp:ObjectDataSource
id="ods1"
runat="server"
selectmethod="gg"
typename="index" />
并告诉它使用您的gg()
方法(您在后面的代码中定义),并将ObjectDataSource
绑定到DropDownListControl:
<asp:DropDownList
ID="sd"
DataSourceId="ods1"
DataTextField="Name"
DataValueField="Name"
runat="server" />
请注意,您需要再次指定DropDownList控件的DataTextField
和DataValueField
属性。