Asp.Net - Write True/False on UI based on boolean value of checkbox - asp.net

I am working on this form in VS2012 and SQL Server 2008R2. The table gets the bit value of true or false. In the Gridview itemtemplate, instead of displaying the empty checkbox I want to say "True or False". How can I do that? This is what I have done so far:
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# (Eval("Banned").ToString())%>' />

You need to set the Text property of the CheckBox control, like this:
<asp:CheckBox ID="CheckBox1" runat="server"
Checked='<%# DisplayTruth(Eval("Banned").ToString()) %>'
Text='<%# DisplayTruthValue(Eval("Banned").ToString()) %>' />
Now in your code-behind, create the two methods, like this:
protected bool DisplayTruth(string banned)
{
if(banned == "0")
{
return true;
}
return false;
}
protected string DisplayTruthValue(string banned)
{
if(banned == "0")
{
return "True";
}
return "False";
}
I recommend this approach for the following reasons:
The markup does not contain conditional/ternary logic
It is easier to debug the logic versus embedded code blocks
You can leverage the power of Visual Studio compiler to catch syntax errors at compile-time versus run-time errors when the logic is embedded into the binding syntax of the markup

I found this information and it is working. Also I changed asp:checkbox to asp:label. However I want to display "No" instead of "False" so I changed "False" to "No" but still my app says "False".
<asp:Label ID="CheckBox1" runat="server" Text='<%# IIf(Convert.ToString(Eval("Banned")) = "", "No", Eval("Banned"))%>' />

Related

Is it possible to use DataBinding to evaluate Controls on .aspx page?

I'm not sure if I am asking this question correctly. I know that I can accomplish what I need in code behind, but I'm wondering if this is possible. I want to hide a control if there is a value in another control. I know I can use databinder.eval in a repeater, but can I use it just for a normal asp control on the page?
In other words, I want to do something like this:
<asp:TextBox runat="server" ID="ConditionalText" Text="Show if other value is empty" Visible ='<%# testValue.Text != "" ? false : true %>'></asp:TextBox>
<asp:TextBox runat="server" ID="testValue"></asp:TextBox>
I tried just the way I have it above, and <%# testValue. exposed available properties of "testValue" TextBox so I thought it might work. It didn't throw any errors but it did not show/hide the textbox. I'm just wondering if this is possible and what I would have to do to accomplish this.
Any assistance is greatly appreciated.
It can work, but since you are using a databinding expression outside a GridView, Repeater etc. you have to call it manually.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//rest of the code
}
//call databind manually
DataBind();
}
PS better to use IsNullOrEmpty instead of = ""
<asp:TextBox runat="server" ID="ConditionalText" Text="Show if other value is empty"
Visible='<%# !string.IsNullOrEmpty(testValue.Text) ? false : true %>'></asp:TextBox>

Using iif function in checkbox

I am working in a project where I need to display data from database in a gridview. The gridview contains varchar fields could be whether YES or NO. So I want to display rather than the text, checkbox. When its YES check box will be checked, when its NO check box will be unchecked.
My asp.net
<asp:CheckBox ID="chkCheck" runat="server" Checked='<%#"IIF(Eval("Check")="YES",true,false)%>' Width="80px" Enabled="false"/>
I am getting this error:
Character constant must contain exactly one character.
Is there any alternative option would solve my issue?
You can simply use this (for VB.NET)
Checked='<%# Eval("Check")="YES" %>'
For null values try
Checked='<%# Convert.ToString(Eval("Check"))="Yes" %>'
I'm not sure about your error, but do you need the IIF? I'm no expert in ASP, I'm relatively new to it, but why can't you just do Checked='<%# Eval("Checked") == "yes" %>'? And beyond that what about Checked='<%# Item.Checked == "yes" %>'?
Performance hint: Use DataRowView instead of Eval within the GridView control:
Checked='<%# (((System.Data.DataRowView)Container.DataItem)["Check"].ToString() == "YES") ? true : false %>'

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.

Listview/DetailsView: Hide a null field

I imagine this is quite a common problem, but as yet I haven't found an elegant solution.
I have a number of instances where I have either a ListView or a DetailsView control that is bound to a SQL Server SProc. The problem I have is that there are numerous instances where, when a column is Null, I want to display something different in the UI. A typical example would be where I have a URL column that is rendered as a LinkButton (in the ListViews) or as a HyperLinkField (in the DetailsViews) - when a Null URL is returned, I'm rendering links with no src attribute. Ideally, I's want to display nothing in this field in such a scenario.
In each of these cases, when a null value is returned, how can I skip/alter the rendering of that item?
Thanks in advance.
Update: I haven't had chance to actually try these out, but all helpful suggestions. I think I like Ricks answer the best, but thanks again to the others...
Markup:
<asp:HyperLink id="whatever" runat="server"
NavigateURL='<%# Eval("url") %>' Visible='<%# IsVisible(Eval("url")) %>' />
Code behind:
protected bool IsVisible(object obj)
{
bool result = false;
string url = (string)obj;
if(!string.IsNullOrEmpty(url))
{
result = true;
}
return result;
}
Within a Template bind also to Visibility
<asp:HyperLink ... NavigateURL=<%# Eval("url") %> Visible=<%# Eval("url") != null %> />
Warning: not Tested, could also be
<asp:HyperLink ... NavigateURL=<%# Eval("url") %> Visible=<%# Eval("url") != DBNull.Value %> />
I suppose you could either create a method in your code behind that takes the value as a parameter and returns a link if it's not null. Or you could tap into the data bound event of the Listview, examine the value and hide the control if it's null.
Neither a very elegant solutions, but I guess that's up to you to decide. :)

ASP.NET GridView ItemTemplate

OK I have a GridView and there is a column that I want to be a link if a file exists, otherwise I just want it to be a label. Right now I am changing the controls on RowDataBound event handler using the Row passed in the args. I am not a big fan of this as I am hard coding the column ID, and if it ever changes I will need to remember to change this code. I was hoping I could do a conditional in the asp code to add a link if a property value is not null otherwise add a label. Is this possible? Any different solutions?
I would like something like this:
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<%# if (Eval("LogFileName") == null)
<%#{
<asp:LinkButton ID="LogFileLink" runat="server" CommandArgument='<% #Eval("LogFileName") %>' CommandName="DownloadLogFile" Text='<%# Blah.NDQA.Core.Utilities.GetEnumerationDescription(typeof(Blah.NDQA.Core.BatchStatus), Eval("Status")) %>'>
<%# }
<%# else
<%#{
<asp:Label ID="LogFileLabel" runat="server"Text='<%# Blah.NDQA.Core.Utilities.GetEnumerationDescription(typeof(Blah.NDQA.Core.BatchStatus), Eval("Status")) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
You can continue to use RowDataBound event but in your aspx you add:
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
In your C# code something like that:
if (LogFileName) {
LinkButton ctrl = new LinkButton();
ctrl.CommandArgument= ...;
ctrl.CommandName= ...;
} else {
Label ctrl = new Label();
ctrl.Text= ...;
}
// You have to find the PlaceHolder1
PlaceHolder1.Controls.Add(ctrl);
In this way you don't have to hard coding the column ID
I know this is a little old now but just in case someone else stumbles across this as I did when looking for an answer to a similar question, I found you can do something like this:
<ItemTemplate>
<asp:ImageButton ID="btnDownload" runat="server"
CommandName="Download"
CommandArgument='<%# Eval("Document_ID") & "," & Eval("Document_Name") %>'
ImageUrl="download.png" ToolTip='<%#"Download " & Eval("Document_Name") %>'
Visible='<%# Not(Eval("Document_ID") = -1) %>' />
</ItemTemplate>
i.e. set the Visible property to evaluate a boolean expression based on your field. If you wanted to display something instead of the download link or button, such as a "Not available" label, then you would just set its Visible property to the opposite boolean expression to your download link. (This is VB.NET not C#, but you get the idea.)
If you're going to be doing this a lot, I suggest writing your own field. The simplest approach is probably to make a NullableHyperlinkField inheriting from HyperlinkField, and render out a plain string if the anchor's URL would otherwise be null.
Use properties on the page to determine if you want to show the label or the link
<asp:GridView ID="gv" runat="server">
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:LinkButton runat="server" Visible='<%# ShowLink %>' PostBackUrl="~/Aliases.aspx" >This is the link</asp:LinkButton>
<asp:Label runat="server" Visible='<%# ShowLabel %>'>Aliases label</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The add the properties ShowLink and ShowLable toyour code behind
public bool ShowLabel
{
get
{
//determine if the label should be shown
return false;
}
private set
{
//do nothing
}
}
public bool ShowLink
{
get
{
//determine if the link should be shown
return true;
}
private set
{
//do nothing
}
}

Resources