如何在ASP.NET中的标签中显示登录的用户名? [英] how to display logged in user's name in a label in ASP.NET?

查看:415
本文介绍了如何在ASP.NET中的标签中显示登录的用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用asp.net web form开发一个网站。在身份验证之后,我需要在标签中登录用户的名字。

i尝试使用以下代码和查询来显示但是失败.. < br $>
-----------

i have been developing a website using asp.net web form.after authentication i need the logged in user's name in a label.
i tried the following code and query to display but failed..
-----------

protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con= new SqlConnection();
        con.ConnectionString=@"Data Source=KAARTHICK-PC\KAARTHICKRAMAN;Initial Catalog=sample;Integrated Security=True";
        con.Open();
        string query="select UserName from Login123 where UserName='"+Label2.Text+"' ";
        SqlDataAdapter ada=new SqlDataAdapter(query,con);
        DataTable dt=new DataTable();
        ada.Fill(dt);
        con.Close();
    }



----------

如果你帮帮我,我将不胜感激。提前谢谢!


----------
it will be grateful if you help me out. thanks in advance !

推荐答案

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = @"Data Source=KAARTHICK-PC\KAARTHICKRAMAN;Initial Catalog=sample;Integrated Security=True";
            using (con)
            {               
                con.Open();
                string query = "select UserName from Login123 where UserName='" + Your username text box.Text + "' ";
                SqlCommand cmd = new SqlCommand(query, con);
                string strUsrNm =Convert.ToString( cmd.ExecuteScalar());
                Label2.Text = strUsrNm;
                con.Close();
            }
        }
        catch
        {
        }
        finally
        {
            
        }
    }





像这样更改你的代码。如果没有必要,你不应该使用数据表。



Change your code like this. you should not use data table if it is not necessary.


在ASP.NET中探索会话 [ ^ ]



为了您的需要,最好使用会话变量。
Exploring Session in ASP.NET[^]

For your need its better to use session variable.


Hi


更好的方法是在成功登录后,您可以将用户名存储到Session变量中,并且

使用此变量来设置标签的Text属性,如下所示



Hi
Better way is after successful login you can store user name to a Session variable and
use this variable to set Text property of the label like this

Session["username"] = txtUser.Text;





其中txtUser是登录页面中的文本框,您在其中输入用户名



然后在内页(或母版页)中您可以将标签文本设置为下面





where txtUser is the textbox in login page where you enter user name

then in the inner pages (or in the master page) you can set label text as below

lblUser.Text = Session["username"].ToString();


这篇关于如何在ASP.NET中的标签中显示登录的用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆