How do I access a c# variable’s value in an .aspx page?

The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).

we need to access the c# variable in .aspx page at the time we have problem

Please guide us?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It would help if you gave more detail about what you’re trying to do, however you can try this:

First make any variables you want to access in your aspx markup protected.

Then in the page_load method, call DataBind();

Then in your markup you can do this:

<%# VariableName %>

The “<%=” sequence can only be used within certain contexts in server controls. The sequence “<%#” is for DataBound controls and can be used in any context in ASPX page markup. Calling DataBind(); allows you to use this (almost) anywhere on the page.

Method 2

You’ll need something on the page that can be data bound. Bind that object to it’s data source and then you can do an “Eval” on it in the .aspx.

For example, if you have bound your control (presumably in the code-behind) to an object that has a property called “Author”, you can display it in the following manner:

<asp:TableRow ID="trwMsgAuthor" runat="server">
   <asp:TableCell ID="TableCell2" runat="server" Width="1in">Author:</asp:TableCell>
   <asp:TableCell runat="server" ID="celMsgAuthor"><%#Eval("Author")%></asp:TableCell>
</asp:TableRow>

The Table in this example is part of an Accordion control where the “.DataSource” property was set to a generic list of objects, of which “Author” was one of the properties.

Method 3

In your ASPX, but a <asp:literal runat=server> control around your <%=x %> code.

Method 4

Declare C# code behind variable either public or protected and then us it in <% %> block.
e.g. <%= strMyCodebehindvariable%> or <%# strMyCodebehindvariable%>. If you are using second option then you must call DataBind() method in page load.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x