Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to display a session value in an ASP textbox

A basic question but there is no such question on Stack Overflow (for ASP.NET)

<asp:TextBox ID="txtUserName" runat="server" Text=<% Session["UserName"] %> >

I did this a week ago, now something is wrong. It should be simple. I also tried <%= %>, it did not work either. Putting a single quote around '<% %>' gives binding error. Help

like image 885
Hammad Khan Avatar asked Jul 22 '11 13:07

Hammad Khan


People also ask

How do I display session variables in ASPX page?

on button click in Home page & view session value in other pages. Are you sure that the session variable is set before the page is rendered? If not the session is empty and it will display nothing or throw an exception.

Can we use session in ASPX page?

You can't, JavasSript is used for client side scripting on the browser, and cannot access a Session object from a server.


3 Answers

I normally hide the implementation details from the aspx code with a property:

.cs file

public string UserName { get { return Session["UserName"]; } }

.aspx

<asp:TextBox ID="txtUserName" runat="server" Text='<%= UserName %>' >
like image 93
asawyer Avatar answered Oct 01 '22 10:10

asawyer


What I did was pulled the text box in C# code and set it text value to the session. Example:

txtUserName.text = Session["UserName"];

Use it in one of the function which checks the session values or you can use in page_load function (the default function for every page)

like image 39
Hammad Khan Avatar answered Oct 01 '22 10:10

Hammad Khan


Now I think your code should look like <asp:TextBox ID="txtUserName" runat="server" Text='<%# Session["UserName"] %>' >

I always forget the sintax for inline code, this information could be helpfull I think.

like image 32
Ernesto Avatar answered Sep 30 '22 10:09

Ernesto