解决此对象引用未设置为对象实例的问题
本文关键字:对象 实例 问题 设置 对象引用 解决 | 更新日期: 2023-09-27 18:01:10
基本上,我只是在写一些代码来更新配置文件。但我得到了这个错误,它说"对象引用没有设置为对象的实例"。但我已经试着找到这个错误两天了,但我仍然坚持这个错误。请帮我解决这个错误:(谢谢…
输出:
查看输出
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;
}
}
}
您没有对任何会话进行null检查。如果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;