Visual StudioでASP.NETプロジェクトを作成するときの既定のWebサイトテンプレートには、LoginViewにログインしたときにユーザーのユーザー名が表示されます。これをユーザーの名に置き換えたいと思います。私はこれをデータベースに保存しているので、Site.masterページで次のことを試しました(ページのonloadで):
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();を使用しようとしました。しかし、それはうまくいきませんでした。
誰かが私がこれを機能させる方法について何か提案がありますか?
また、これは正しいアプローチですか?確かに、ファーストネームをロードし、ユーザーが別のページに移動するたびにこれをリロードしない(したがって、データベースに対するクエリの数を減らす)より効率的な方法がありますか?