[英]IndexOutOfRange exception in SqlDataReader in asp.net c#
我受夠了這個錯誤。 在登錄時,我正在對用戶進行身份驗證,然后在會話變量中加載一些重要信息。 我在 IIS 上托管我的應用程序,客戶端計算機通過 IP 地址使用該應用程序。 這是我的 C# 代碼...
protected void btnLogin_Click(object sender, EventArgs e)
{
Session["UserName"] = txtUserName.Text;
string DefaultYear = GetDefaultFinYear();
if (DefaultYear != string.Empty)
{
DefaultYear = "connect" + DefaultYear;
Connections.Init(DefaultYear);
SqlDataAdapter adp = new SqlDataAdapter();
SqlDataReader dr = null;
try
{
adp = new SqlDataAdapter("CheckLogin_sp", Connections.Connection[Session["UserName"].ToString()]);
adp.SelectCommand.Parameters.AddWithValue("@UserName", txtUserName.Text.Trim());
adp.SelectCommand.Parameters.AddWithValue("@Pwd", txtPassword.Text.Trim());
adp.SelectCommand.Parameters.AddWithValue("option", "Authenticate".Trim());
adp.SelectCommand.CommandType = CommandType.StoredProcedure;
if (Connections.Connection[Session["UserName"].ToString()].State == ConnectionState.Closed)
{
Connections.Connection[Session["UserName"].ToString()].Open();
}
dr = adp.SelectCommand.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Session["Name"] = dr[0].ToString();
Session["CompanyName"] = dr[1].ToString();
Session["UserId"] = dr[2].ToString();
Session["Center"] = dr[3].ToString();
Session["ClientCode"] = dr[4].ToString();
Session["UserImage"] = dr[5].ToString();
Session["CurrentDatabase"] = dr[6].ToString();
Connections.BillReport = dr[7].ToString();
Connections.DuesReport = dr[8].ToString();
Connections.GeneralReport = dr[9].ToString();
Connections.PendingReport = dr[10].ToString();
Connections.RadiologyReport = dr[11].ToString();
Connections.HistoReport = dr[12].ToString();
}
Session["value"] = "admin";
Response.Redirect("~/Masters/home.aspx", false);
}
else
{
MessageBox.Show("Invalid Password");
txtUserName.Text = string.Empty;
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
Connections.Connection[Session["UserName"].ToString()].Close();
adp.Dispose();
dr.Close();
dr.Dispose();
}
}
else
{
MessageBox.Show("Invalid UserName");
}
}
並非每次出現此錯誤,但有時當多台計算機訪問應用程序時,此錯誤會出現在以下行中
Session["Name"] = dr[0].ToString();
注意:-一旦發生此錯誤,只有在服務器計算機重新啟動時才會解決。
我相信用事務將您的代碼包裝在存儲過程中可以解決您的問題。
BEGIN TRY
BEGIN TRANSACTION CheckLogin
--Existing SQL code
COMMIT TRANSACTION CheckLogin
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION CheckLogin
END CATCH
從 Web 應用程序調用的所有存儲過程都應使用事務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.