'System.Data.DataRowView' in DropDownList
本文关键字:DropDownList in System Data DataRowView | 更新日期: 2023-09-27 18:22:49
我无法将数据绑定到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);
}
您不会在SQL语句中返回名为_Deptid
的列。
您的SQL语句应为:
select _program.Name, _program._Deptid
from _program,_Department
where _program._Deptid = _Department._DeptId
正如Stackoverflow User所提到的,通过使用using
语句,这将自动处理对象。你正在做的另一件事:
if (dt.Rows.Count == 0)
但你里面没有代码。无论你是否在实际代码中这样做,但如果你打算将其留空,最好这样做:
if (dt.Rows.Count > 0)
{
DropDownList.DataTextField = "Name";
DropDownList.DataValueField = "_DeptID";
DropDownList.DataSource = dt.DefaultView;
DropDownList.DataBind();
}
- select语句中缺少列_Dept
-
缺少对对象的处理。所以你可以用两种方式
(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以及
将SQL更改为:
select _Program.Name, _Program._DeptId from _program,_Department where _program._Deptid = _department._DeptId
尝试将代码修改为这样,您缺少_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);
}