在人们将其标记为重复之前:在app.config文件中已将MultipleActiveResultSets设置为true,因此这不是原因:)
我正在尝试使用一个方法,该方法应该使用特定的UserId从我的数据库的Users表中的一行返回byte []并将其转换为List。每当我尝试使用此方法时,我都会收到标题中声明的错误。我希望你能帮忙:)下面是提到的方法,从byte []转换为List的方法,以及在调用此方法的eventhandler中使用的一些方法。希望你们能帮助:)提前谢谢!
导致错误的方法(特别是if(rdr.Read())中的行)
public List<int> GetHistory(string username, string password)
{
List<int> liste = new List<int>();
cmd = new SqlCommand("select History from dbo.Users where Username = @uname and Password = @pword", conn);
cmd.Parameters.AddWithValue("@uname", username);
cmd.Parameters.AddWithValue("@pword", password);
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
liste = ConvertFromByteArray(cmd.ExecuteScalar() as byte[]);
}
rdr.Close();
conn.Close();
return liste;
}
转换方法:
public List<int> ConvertFromByteArray(byte[] array)
{
var mStream = new MemoryStream();
var binFormatter = new BinaryFormatter();
mStream.Write(array, 0, array.Length);
mStream.Position = 0;
var liste = binFormatter.Deserialize(mStream) as List<int>;
return liste;
}
我打算在以下方法中使用该方法的eventhandler的代码:
private void btn_viewhistory_Click(object sender, EventArgs e)
{
string uname = dbConnection.GetUsername(Convert.ToInt32(txt_id.Text));
string pword = dbConnection.GetPassword(Convert.ToInt32(txt_id.Text));
txt_history.Text =
Convert.ToString(dbConnection.GetHistory(uname, pword)[0] + Environment.NewLine +
dbConnection.GetHistory(uname, pword)[1] + Environment.NewLine +
dbConnection.GetHistory(uname, pword)[2]);
}
在事件处理程序中也使用的方法GetUsername和GetPassword:
public string GetUsername(int id)
{
string username = "";
cmd = new SqlCommand("select Username from dbo.Users where UserId = @id", conn);
cmd.Parameters.AddWithValue("@id", id);
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
username = rdr.GetString(rdr.GetOrdinal("Username"));
}
rdr.Close();
conn.Close();
return username;
}
public string GetPassword(int id)
{
string password = "";
cmd = new SqlCommand("select Password from dbo.Users where UserId = @id", conn);
cmd.Parameters.AddWithValue("@id", id);
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
password = rdr.GetString(rdr.GetOrdinal("Password"));
}
rdr.Close();
conn.Close();
return password;
}