基本上我正在编写一些代码来仅更新配置文件。但是我得到了这个错误并且它说"对象引用未设置为对象的实例"。但我一直试图找到这个错误2天但仍然坚持这个错误。请帮我解决这个错误:(谢谢..
输出:
Asp.net.cs代码:
public partial class EditProfile : System.Web.UI.Page
{
SqlConnection conn = null;
SqlCommand cmd = null;
string connectionString = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "SELECT * FROM Staff";
string id = Session["StaffId"].ToString();
Session["StaffId"] = id;
try
{
cmd = new SqlCommand(sql, conn);
conn.Open();
dr = cmd.ExecuteReader();
dr.Read();
id = dr["StaffId"].ToString();
tbStaffName.Text = dr["StaffName"].ToString();
tbPassword.Text = dr["Password"].ToString();
tbEmail.Text = dr["Email"].ToString();
tbPhoneNo.Text = dr["PhoneNo"].ToString();
ddlTitle.SelectedItem.Text = dr["Title"].ToString();
dr.Close();
}
catch (Exception ex)
{
lblOutput.Text = "Error Message:" + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff SET Username=@username, Password=@Pwd, StaffName=@staff, Email=@email, PhoneNo=@phone, Title=@title ";
sql += " WHERE StaffId=@id";
string title= ddlTitle.SelectedItem.Text;
string id = Session["StaffId"].ToString();
Session["StaffId"] = id;
string username = Session["Username"].ToString();
Session["Username"] = username;
try
{
cmd = new SqlCommand(sql, conn);
if(username != null)
{
cmd.Parameters.AddWithValue("@username", username);
}
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@staff", tbStaffName.Text);
cmd.Parameters.AddWithValue("@Pwd", tbPassword.Text);
cmd.Parameters.AddWithValue("@email", tbEmail.Text);
cmd.Parameters.AddWithValue("@phone", tbPhoneNo.Text);
cmd.Parameters.AddWithValue("@title", title);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.Text = "Record update successfully";
}
}
catch (Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
try
{
SqlDSEditProfile.Update();
lblOutput.Text = "Application update";
}
catch (Exception ex)
{
lblOutput.Text = ex.Message;
}
}
}
答案 0 :(得分:0)
您没有对任何会话进行空检查。如果StaffId或Username不存在,则会抛出该错误。先试试这个。
string id = String.Empty;
if (Session["StaffId"] != null)
{
id = Session["StaffId"].ToString();
}
Session["StaffId"] = id;
string username = String.Empty;
if (Session["Username"] != null)
{
username = Session["Username"].ToString();
}
Session["Username"] = username;