如何将方法绑定到dropdownlist中

时间:2014-09-14 18:58:34

标签: c# asp.net

我需要使用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控件中显示任何内容。 我的错误在哪里?

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案是在gg()事件中从代码隐藏中绑定 Page_Load方法。首先,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 object(例如在关闭正文标记之前):

<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控件的DataTextFieldDataValueField属性。