how to display a session value in an ASP textbox - asp.net

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

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 %>' >

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)

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.

Related

ASP.NET WebForms: Format texts for strong typed ListView fields

I tha the following markup:
<asp:ListView ItemType="MyNamespace.MyEntity" runat="server" >
<listiview tags>
<asp:Label ID="lblDebtAmount" runat="server" Text="<%#:string.Format("
{0:C}",Item.Amount) %>"
</listiview tags>
</asp:ListView>
In the given example i'm trying to apply currency format to the text rendered by a label, but i'm after achieve this for text controls in general (Labels, Literal, Textbox, etc) . The problem is that the above produce the following server error:
"Analizer Error Mesage: Invalid Server Tag"
The same result if i try with the following:
<asp:Label ID="lblDebtAmount" runat="server" Text="<%#:string.Format("
{0:C}",Item.Amount.ToString("C")) %>"
Another approach, this time i get runtime exception:
<%# String.Format("{0:C}", Eval(Item.Amount.ToString() )) %>
DataBinding: 'System.Data.Entity.DynamicProxies... does not contains a
property named '500000,00'.
Another approach that i have tryied is formating the entity's property:
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Amount { get; set; }
That does not produce any error but neither got the text formated, the label just render the value without format
The only thing that seems to work is using the old way databinding:
<%# String.Format("{0:C}", Eval("Amount")) %>
But if i'm going to use strong typed binding for Webforms i dont want to be using strings to resolve properties value anymore:
I think this has to be dead easy, any thought?
Try switching from double quotes to single quotes for the text property, the way you currently have it ends the string early so the text property is actually just "<%#:string.Format("
<asp:ListView ItemType="MyNamespace.MyEntity" runat="server" >
<listiview tags>
<asp:Label ID="lblDebtAmount" runat="server" Text='<%#:string.Format("
{0:C}",Item.Amount) %>'
</listiview tags>
</asp:ListView>

Tuncate string in ASP.NET using VB.NET

I made a function to truncate a string in the code behind file. But how do i use it in the aspx file?
This is the textbox:
<asp:TemplateField HeaderText="page" HeaderStyle-Wrap="true">
<ItemTemplate>
<a href='<%# makepageURL( Eval("page") )%> '>
<%# Eval("page")%>
</a>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtpage" TextMode="SingleLine" Rows="1" Width="100%" runat="server" Text='<% #Bind("page") %>' />
</EditItemTemplate>
</asp:TemplateField>
And this is my function:
Public Function TrimString(ByVal Value As String, ByVal Length As Integer) As String
If Value.Length > 20 Then
Return Value.Substring(Value.Length - (20 - 3)) + "..."
End If
Return Value
End Function
It's not an issue of how to use it, but actually when to use it?
If you had a regular span, you could do this:
<span><%: TrimString("somestring") %></span>
But this is a TextBox your dealing with (user input).
When should it truncate?
On Form Submit? (that would make sense).
As they type (well then you'd need to use JavaScript).
By the looks of your code snipper, your using a FormView.
So i wouldn't be calling it from the ASPX (which the equivalent of executing code during Page Render), i would be calling it during the Edit/Submit event, server-side event handler.
In other words, truncate the value the user put in, after they have submitted the form and before you persist to the database.

ASP.NET Binding integer to CheckBox's Checked field

I have a following ListView item template, in which I am trying to bind integer value to Checked property of CheckBox.
IsUploaded value contains only 0 and 1...
<asp:ListView ID="trustListView" runat="server">
<ItemTemplate>
<asp:CheckBox ID="isUploadedCheckBox" runat="server"
Checked='<%# Bind("IsUploaded") %>' />
</ItemTemplate>
</asp:ListView>
But ASP.NET complains that
Exception Details: System.InvalidCastException: Sepcified cast is not valid
Even though following code using DataBinder.Eval() works,
I need to have a 2-way binding, thus need to use Bind().
<asp:CheckBox ID="isUploadedCheckBox2" runat="server"
Checked='<%# Convert.ToBoolean(
DataBinder.Eval(Container.DataItem, "IsUploaded"))) %>' />
How can I convert 0's and 1's to boolean using Bind()?
[ANSWER]
I have extended auto-generated type through partial class by adding a new property mentioned in the answer by Justin
If you're willing to change the class, add a property on the class that's a boolean
public bool IsUploadedBoolean
{
get { return IsUploaded != 0; }
set { IsUploaded = value ? 1 : 0; }
}
If not, you may have success with a TypeConverter:
Create a custom TypeConverter which will handle 0 and 1 to boolean conversions
Stick the TypeConverterAttribute on the IsUploaded property to direct .NET to your custom typeconverter.
How about adding a property to your class which does the conversion?
public bool IsUploadedBool
{
get { return IsUploaded == 1; }
}
and then bind to this IsUploadedBool property instead of directly to the underlying INT.
Marc
Kind of a cheesy work around would be to use a drop down list with list items to give the same effect:
<asp:DropDownList ID="ddlBool" runat="server" SelectedValue= '<%# Bind("IsUploaded") %>'>
<asp:ListItem Text="True" Value="1" />
<asp:ListItem Text="False" Value="0" />
</asp:DropDownList>
For more information visit:
http://dhondiyals.wordpress.com/2010/05/03/binding-checkbox-with-integer-value-in-gridviewtrick/
How about (btw i am using a stored procedure)
Aspx page
<asp:CheckBox ID="social_facebook" runat="server" Checked='<%# Bind("True") %>' />Facebook
Code behind
cmd.Parameters.Add("#p_facebook", SqlDbType.Bit).Value = social_facebook.Checked;
Solution:
Hi, I'm also using Ajax rating inside a GridView and I ran into this problem. After looking through several forums, I tried this and it worked for me. I hope it helps you:
<%# Convert.ToInt32(Eval("EVALUATION")) %>
returns an integer, since you're using Checked which is an integer.

Can I use <%= ... %> to set a control property in ASP.NET?

<asp:TextBox ID="tbName" CssClass="formField" MaxLength="<%=Constants.MaxCharacterLengthOfGameName %>" runat="server"></asp:TextBox>
The code above does not work. I can set the MaxLength property of the textbox in the code behind but i rather not. Is there away I can set the MaxLength property in the front-end code as above?
You could use DataBinding:
<asp:TextBox
ID="tbName"
CssClass="formField"
MaxLength="<%# Constants.MaxCharacterLengthOfGameName %>"
runat="server">
</asp:TextBox>
and in your code behind Page_Load call:
tbName.DataBind();
or directly databind the page:
this.DataBind();
The <%= expression %> syntax is translated into Response.Write(expression), injecting the value of expression into the page's rendered output. Because <%= expression %> is translated into (essentially) a Response.Write these statements cannot be used to set the values of Web control properties. In other words, you cannot have markup like the following:
<asp:Label runat="server" id="CurrentTime" Text="<%= DateTime.Now.ToString() %>" />
Source: https://web.archive.org/web/20210513211719/http://aspnet.4guysfromrolla.com/articles/022509-1.aspx
Try to use custom expression builder:
// from http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : System.Web.Compilation.ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}
And then use it like
<asp:TextBox ID="tbName" CssClass="formField" MaxLength="<%$ Code: Constants.MaxCharacterLengthOfGameName %>" runat="server"></asp:TextBox>
As Ropstah said, it isn't going to work with the <%= expression %> syntax.
But you could probably use databinding, which just requires that you use the <%# expression %> syntax and then call MyTextBox.Databind in CodeBehind.
Of course, at that point it might be more clear to just do the whole operation in CodeBehind.
Another alternative: if you really want this to be declarative, you could get away from the Label and embed your expression in a span tag.That way you still get to apply CSS, etc and I think the <%= expression %> syntax would work.
Why don't you just set it in the Page_Init callback function in the code behind?
This example is geared towards getting the max length from underlying sql types in linq. But you should be able to customise it to your needs
http://blog.binaryocean.com/2008/02/24/TextBoxMaxLengthFromLINQMetaData.aspx
It looks like you want to be able to control the max length of a specific type of text box from a single location so that if that max length needs to change, you only need to change it in one place.
You can accomplish this by using a skin file. You set the max length in the skin file as you would normally and then any textbox that uses that max length would use the skin. If the length changes then you only need to change the skin file.
You can do it with databinding
<asp:TextBox
ID="tbName"
CssClass="formField"
MaxLength='<%# Constants.MaxCharacterLengthOfGameName %>'
runat="server" />
Then in the code behind
protected void Page_Load(object sender, EventArgs e) {
Page.DataBind();
}
You can embed "normal" code in the .aspx file if you so want, like:
<%
tbName.MaxLength = Constants.MaxCharacterLengthOfGameName
%>
<asp:TextBox ID="tbName" CssClass="formField" runat="server"></asp:TextBox>
This harkens back to an older style "classic" ASP way of doing this.

Formatting DataBinder.Eval data

How can I format data coming from a DataBinder.Eval statement in an ASPX page?
For example, I want to display the published date of the news items in a particular format in the homepage. I'm using the ASP.NET 2.0 Repeater control to show the list of news items.
The code for this goes like this:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
<HeaderTemplate><table cellpadding="0" cellspacing="0" width="255"></HeaderTemplate>
<ItemTemplate>
<tr><td >
<a href='/content/latestNews.aspx?id=<%#DataBinder.Eval(Container.DataItem, "id") %>'>
<asp:Label ID="lblNewsTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "title") %>'></asp:Label>
</a>
</td></tr>
<tr><td>
<asp:Label ID="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate"))%>'></asp:Label>
</td></tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate></asp:Repeater>
Is there a way I could call a custom method with the DataBinder.Eval value as its parameter (something like below)?
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
If yes, then where do I write the GetDateInHomepageFormat method? I tried out in the code behind page but got a run time error?
If this is not possible, is there a way to do inline formatting?
There is an optional overload for DataBinder.Eval to supply formatting:
<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>
The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:
<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>
After some searching on the Internet I found that it is in fact very much possible to call a custom method passing the DataBinder.Eval value.
The custom method can be written in the code behind file, but has to be declared public or protected. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be private.
So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:
default.aspx
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
default.aspx.cs code:
public partial class _Default : System.Web.UI.Page
{
protected string GetDateInHomepageFormat(DateTime d)
{
string retValue = "";
// Do all processing required and return value
return retValue;
}
}
Hope this helps others as well.
Why not use the simpler syntax?
<asp:Label id="lblNewsDate" runat="server" Text='<%# Eval("publishedDate", "{0:dddd d MMMM}") %>'</label>
This is the template control "Eval" that takes in the expression and the string format:
protected internal string Eval(
string expression,
string format
)
http://msdn.microsoft.com/en-us/library/3d2sz789.aspx
You can use a function into a repeater like you said, but notice that the DataBinder.Eval returns an object and you have to cast it to a DateTime.
You also can format your field inline:
<%# ((DateTime)DataBinder.Eval(Container.DataItem,"publishedDate")).ToString("yyyy-MMM-dd") %>
If you use ASP.NET 2.0 or newer you can write this as below:
<%# ((DateTime)Eval("publishedDate")).ToString("yyyy-MMM-dd") %>
Another option is to bind the value to label at OnItemDataBound event.
This line solved my problem:
<%#DateTime.Parse(Eval("DDDate").ToString()).ToString("dd-MM-yyyy")%>
To format the date using the local date format use:
<%#((DateTime)Eval("ExpDate")).ToString("d")%>
How to Format an Eval Statement to Display a Date using Date Locale
Thanks to all. I had been stuck on standard format strings for some time. I also used a custom function in VB.
Mark Up:-
<asp:Label ID="Label3" runat="server" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, "psWages1D")) %>'/>
Code behind:-
Public Function fLabel(ByVal tval) As String
fLabel = tval.ToString("#,##0.00%;(#,##0.00%);Zero")
End Function
Text='<%# DateTime.Parse(Eval("LastLoginDate").ToString()).ToString("MM/dd/yyyy hh:mm tt") %>'
This works for the format as you want
<asp:Label ID="ServiceBeginDate" runat="server" Text='<%# (DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:yyyy}") == "0001") ? "" : DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:MM/dd/yyyy}") %>'>
</asp:Label>
You can use it this way in aspx page
<%# DataBinder.Eval(Container.DataItem, "DateColoumnName", "{0:dd-MMM-yyyy}") %>

Resources