我正在尝试编写一个可以在 C# 中填充 DropDownList 或 AJAX ComboBox(而不是具有两个独立的、几乎相同的方法)的方法。我向该方法传递了一个查询字符串、文本字段的名称、值字段的名称以及下拉对象。这是我到目前为止所拥有的:
public static void BindDropDown(string selectCmd, string textField, string valueField, object ddList)
//Populate dropdown list (DropDownList or ComboBox)
{
// var for dropdown object
object _ddl = null;
// Get type of dropdown
if (ddList.GetType() == typeof(DropDownList))
{
_ddl = (DropDownList)ddList;
}
else if (ddList.GetType() == typeof(ComboBox))
{
_ddl = (ComboBox)ddList;
}
// Setup DB connection
SqlConnection dbConn = new SqlConnection(LTConnStr);
SqlCommand myCmd = new SqlCommand(selectCmd, dbConn);
//Set dropdown list params
_ddl.DataTextField = textField;
_ddl.DataValueField = valueField;
try
{
dbConn.Open();
_ddl.DataSource = myCmd.ExecuteReader();
_ddl.DataBind();
}
finally
{
dbConn.Close();
}
} //end method BindDropDown
但我得到错误“'object'不包含'DataTextField'的定义......”。我也尝试过“is”语法:
// Get type of dropdown
if (ddList is DropDownList)
{
_ddl = (DropDownList)ddList;
}
else if (ddList is ComboBox)
{
_ddl = (ComboBox)ddList;
}
结果相同。我知道我很接近,但我无法完全弄清楚。