ASp.net中DropDownList无效的SelectedValue

来源:百度知道 编辑:UC知道 时间:2024/05/29 13:37:06
一段一样的代码,在实验网站的页面中DropDownList能够正常从数据库中绑定值(本页面中只有两个互不相关的DropDownList),但是把代码移植到另一个网站网页中就出现如下提示:
“DropDownListClass”有一个无效 SelectedValue,因为它不在项目列表中。
参数名: value
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.ArgumentOutOfRangeException: “DropDownListClass”有一个无效 SelectedValue,因为它不在项目列表中。
参数名: value

源错误:

行 74: DropDownListClass.DataTextField = "班级名称";
行 75: DropDownListClass.DataValueField = "班级名称";
行 76: DropDownListClass.DataBind();
行 77: myconnection.Close();
行 78: }

数据库代码:
create table ClassInfo(班级名称 nvarchar(10) not null primary key,
所属专业 nvarchar(10) not null,
班主任 nvarchar(5) not null,
学生总数 nchar(3) not null)

create table Teaching(授课老师 nvarchar(5) not null primary key,
所授科目 nvarchar(20) not null,
授课班级 nvarchar(10) not null)

cs文件部分代

SqlDataReader myReader = mycommand.ExecuteReader
DropDownListClass.DataSource = myReader;
//没有 循环
DropDownListClass.DataTextField = "班级名称";
DropDownListClass.DataValueField = "班级名称";
DropDownListClass.DataBind();
因为你的myReader 只有一项有数据呀!你要循环呀
while(myReader.Read())然后填充DropDownListClass

这句 :
DropDownListClass.SelectedIndex =DropDownListClass.Items.IndexOf(DropDownListClass.Items.FindByText("信网051"));
按我的思路来,就不会把 SelectedIndex 放在绑定DropDownList之前。其次你既然未绑定任何值在上面 凭什么去找 "信网051" 我相信DropDownList再智能也是一句一句的执行吧,不会把这句存储起来等你执行完绑定再执行这句?
我没有具体运行过,不过我是不会这样写的。你试一下把这句放到绑定完DropDownList之后看看【两个地方都是这样】。

设置断点跟踪一下 也许就明白了。另外 楼下的说得不错SqlDataReader 虽然读取速度很快但我觉得那只是数据库读取一条数据比较快 若取的数据多了建议换成 OracleDataAdapter 然后 Fill 一个数据集