我无法将数据绑定到Dropdown List
..有人可以解释为什么吗?
错误是:'System.Data.DataRowView' does not contain a property with the name '_DeptID'.
我的代码是:
public class ClassDataManagement
{
public DataTable BindDropDownList(string Sql, DropDownList DropDownList)
{
SqlConnection cn = new SqlConnection(@"Data Source=ABID-PC;Initial Catalog=_uniManagement;Integrated Security=True");
SqlCommand cmd = new SqlCommand(Sql, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 0)
{
}
else
{
DropDownList.DataTextField = "Name";
DropDownList.DataValueField = "_DeptID";
DropDownList.DataSource = dt.DefaultView;
DropDownList.DataBind();
}
return dt;
}
}
protected void Page_Load(object sender, EventArgs e)
{
ClassDataManagement dm = new ClassDataManagement();
dm.BindDropDownList("select _Program.Name from _program,_Department where _program._Deptid = _department._DeptId", DropDownListProgram);
}
答案 0 :(得分:4)
您没有在SQL语句中返回名为_Deptid
的列。
您的SQL语句应为:
select _program.Name, _program._Deptid
from _program,_Department
where _program._Deptid = _Department._DeptId
正如Stackoverflow用户所提到的,通过使用using
语句,这将自动处理您的对象。另一件事,你在做:
if (dt.Rows.Count == 0)
但你里面没有代码。无论您是否使用实际代码,但如果您打算将其留空,建议您执行以下操作:
if (dt.Rows.Count > 0)
{
DropDownList.DataTextField = "Name";
DropDownList.DataValueField = "_DeptID";
DropDownList.DataSource = dt.DefaultView;
DropDownList.DataBind();
}
答案 1 :(得分:3)
缺少对象的处理。所以你可以用两种方式执行它
(a)手动处理
(b)使用陈述
public class ClassDataManagement
{
public DataTable BindDropDownList(string Sql, DropDownList DropDownList)
{
using (SqlConnection cn = new SqlConnection(@"Data Source=ABID-PC;Initial Catalog=_uniManagement;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(Sql, cn))
{
using(SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
DropDownList.DataTextField = "Name";
DropDownList.DataValueField = "_Deptid";
DropDownList.DataSource = dt.DefaultView;
DropDownList.DataBind();
return dt;
}
}
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
ClassDataManagement dm = new ClassDataManagement();
dm.BindDropDownList("select _Program.Name, _program._Deptid from _program,_Department "
+ "where _program._Deptid = _department._DeptId", DropDownListProgram);
}
编辑 - 1
添加 SqlDataAdapter 的使用声明
答案 2 :(得分:3)
将您的SQL更改为:
select _Program.Name, _Program._DeptId from _program,_Department where _program._Deptid = _department._DeptId
答案 3 :(得分:3)
尝试将代码修改为此,您遗漏了_DeptID
protected void Page_Load(object sender, EventArgs e)
{
ClassDataManagement dm = new ClassDataManagement();
dm.BindDropDownList("select _Program.Name,_DeptID from _program,_Department where _program._Deptid = _department._DeptId", DropDownListProgram);
}