我试图让我的应用程序检查我的 SQL 数据库中的 Admins 表,然后获取当前用户所属部门的名称。之后,我想检查另一个表并仅选择属于该部门的新闻项目。
下面显示了我将如何处理它,但是问题在于在 While 循环之外使用 mydepartment 变量(在第二个 SQL 查询中使用)。
除此以外,一切正常。任何帮助,将不胜感激。
public string username = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];
public string mydepartment;
protected void Page_Load(object sender, EventArgs e)
{
lblUser.Text = username.ToString();
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
myConnection.Open();
string selectretrieveSQL = ("SELECT * FROM Admins WHERE userid = '" + username.ToString() + "'");
SqlCommand retrieveinfocmd = new SqlCommand(selectretrieveSQL, myConnection);
SqlDataReader reader = retrieveinfocmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["Department"].ToString();
newItem.Value = reader["userid"].ToString();
UserIds.Items.Add(newItem);
mydepartment = reader["Department"].ToString();
mydepartmentlbl.Text = reader["Department"].ToString();
}
reader.Close();
string selectNewsSQL = ("SELECT * FROM NewsItems WHERE Department = '" + mydepartment + "'");
}