我对 c# 和 asp.net 很陌生,所以请告诉我,如果我给你一些关于我的问题的信息。
当用户登录时,我创建我的用户对象的一个实例,调用我的 getcategories 方法并将用户重定向到另一个页面。像这样:
if (dt.Rows.Count > 0){
user apa = new user();
apa.namn = dt.Rows[0]["FirstName"].ToString() + " " + dt.Rows[0]["LastName"].ToString();
apa.mail = dt.Rows[0]["Email"].ToString();
apa.id = dt.Rows[0]["ID"].ToString();
apa.firstname = dt.Rows[0]["FirstName"].ToString();
apa.lastnamn = dt.Rows[0]["LastName"].ToString();
apa.password = dt.Rows[0]["Password"].ToString();
Session["user"] = apa;
apa.getcategories();
Response.Redirect("visainlagg.aspx");
}
问题是我在“kategorier[i].Name = dt.Rows[i]["Name"].ToString();”上得到“对象引用未设置为对象的实例”-错误 (在 User 类的 for 循环中发生的第一件事)。我不明白为什么 :(
这是 User 类的样子:
public string namn;
public string mail;
public string id;
public string firstname;
public string lastname;
public string password;
public string constr = "secret";
public Post[] poster;
public anvcateg[] kategorier;
public int antalKategorier;
public void getcategories() {
SqlConnection conn = new SqlConnection();
conn.ConnectionString = constr;
SqlCommand com = new SqlCommand();
com.Connection = conn;
com.CommandText = "SELECT * FROM Category WHERE Author= '" + id + "'";
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = com;
DataTable dt = new DataTable();
adp.Fill(dt);
antalKategorier = dt.Rows.Count;
kategorier = new anvcateg[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
kategorier[i].Name = dt.Rows[i]["Name"].ToString();
kategorier[i].ID = dt.Rows[i]["ID"].ToString();
kategorier[i].Description = dt.Rows[i]["Description"].ToString();
kategorier[i].Author = dt.Rows[i]["Author"].ToString();
}
}
getcategories() 使用的 anvcateg 类如下所示:
public class anvcateg
{
public string ID;
public string Name;
public string Description;
public string Author;