在Visual Studio中創建ASP.NET項目時的默認網站模板在LoginView中登錄時顯示用戶的用戶名。我想用用戶的名字來替換它。我有這個存儲在數據庫中,所以在頁面的Site.Master我試過以下(在頁面的onload):在LoginView中顯示用戶名
MembershipUser user = Membership.GetUser();
string id = user.ProviderUserKey.ToString();
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
using (connection)
{
using (SqlCommand con_get = new SqlCommand("SELECT firstname FROM x WHERE userId='" + id + "'", connection)) //Executes SQL command
{
try
{
connection.Open(); //Opens the database connection
using (SqlDataReader reader = con_get.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
Label label1 = (Label)sender;
label1.Text = reader["x"].ToString();
}
}
}
}
catch
{
}
finally
{
connection.Close(); //Closes the database connection
}
}
}
}
catch
{
}
這並不是目前的工作。我也試過不使用發件人,只是嘗試使用label1.Text = reader [「x」]。ToString();但那不起作用。
有沒有人有任何建議我可以做這項工作?
此外,這是正確的方法?當然,有一種更有效的方法來加載第一個名字,而不是每次用戶導航到不同的頁面時重新加載(因此減少了針對數據庫的查詢數量)?
如果您沒有默默丟棄所有可能有用的錯誤消息,這可能會有所幫助。至少將它們記錄到文件或將它們轉儲到屏幕上,因爲這對於幫助調試問題非常有用。 – mellamokb
在調試時,我將它縮小到了在LoginView中設置標籤值的問題。如果我在外面使用標籤,那很好。我正在使用這個:Label new_label =(Label)HeadLoginView.Parent.FindControl(「lbl」); string getPlayerName = reader [「FIRST_NAME」]。ToString(); new_label.Text = getPlayerName; new_label.Visible = true; – Mike91
編輯:通過執行以下操作對它進行排序:標籤name_label =(Label)FindControl(「HeadLoginView」)。FindControl(「login_lbl」);找到標籤,而不是標籤name_label = HeadLoginView.FindControl(「login_lbl」); – Mike91