异常详细信息: System.InvalidOperationException: 在没有任何数据时进行无效的读取尝试。

来源:百度知道 编辑:UC知道 时间:2024/06/22 13:33:23
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["project_systemConnectionString"]);
SqlCommand cmd = new SqlCommand("select * from user_loading where username='" + Session["UserId"].ToString()+ "'",con);

cmd.Connection.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

string staff_name = reader["staff_name"].ToString();

错误信息:
在没有任何数据时进行无效的读取尝试。
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.InvalidOperationException: 在没有任何数据时进行无效的读取尝试。

源错误:

行 22: SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
行 23:
行 24: string staff_name = reader["staff_name"].ToString();
行 25: this.TextBox3.Text= Session["UserId"].ToString();
行 26: Respons

这个问题很简单啊, 你不能保证你Session["UserId"].ToString()+ 里面一定有值,(假如是""。那就读取不到数据的.).

所以在使用SqlDataReader 读取数据的时候要加如下的判断.
while(dr.read())
{
string staff_name = reader["staff_name"].ToString();
行 25: this.TextBox3.Text= Session["UserId"].ToString();
}
必要情况下要加异常处理。 些程序什么情况都要考虑。 这样你的程序才能安全

重装是明知得选择