ASP.NET Binding integer to CheckBox's Checked field - asp.net

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.

Related

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

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"))%>' />

User control (ascx) in asp.net and its bindable properties dont show up in the data container

When I add a user control which has bindable properties to an asp.net page I do not see its bindable properties on the designer's dialog box when I click the edit Data bindings on the Repeater-Listview
should I add any other propery descriptors?
the markup would be like this inside a repeater or similar control
<uc1:Menu ID="Menu1" superman="<% Eval("userid") %>" runat="server" />
on the bindable property I only use
[System.ComponentModel.DefaultBindingProperty("superman")]
[System.ComponentModel.Bindable(true)]
public int superman
{
get;
set;
}
People discuss it here but they couldn't find a solution
I think this might be a problem with Visual Studio, I have not found a way to show the properties of user controls, but still, you can bind the property even when it does not appear in the options box:
This is how you bind it:
In the user control code behind:
[Bindable(true)]
public string MyProperty
{
get
{
return this.lblMessage.Text;
}
set
{
this.lblMessage.Text = value + DateTime.Now.ToString();
}
}
In the ASCX file:
<asp:Label ID="lblMessage" Text="something" runat="server" />
In the ASPX page:
<asp:DataList runat="server" ID="dataList" Width="50%"
DataSourceID="ObjectDataSource1">
<ItemTemplate>
<uc1:WebUserControl1 runat="server" ID="myUC" MyProperty='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:DataList>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
SelectMethod="GetProducts" TypeName="WebApplication1.Repository">
</asp:ObjectDataSource>
Simple just add the property you created in your UC in the tag:
<uc1:WebUserControl1 runat="server" ID="myUC" MyProperty='<%# Eval("Name") %>' />
This is the output:
I think you just make the markup by typing it,
the user control must be drag and drop to the page in the design view.
try this may helps.

NavigateUrl with NavigateUrlFormat populated from AppSettings (dynamically)

I have a gridview with a hyperlink inside an TemplateField. The NavigateUrlFormat will be populated from the Web.Config file, it has the following format:
mysite.com/{0}
Where {0} will be populated from the gridview datasource, however, my current code doesn't work:
<asp:TemplateField HeaderText="WorkOrder #">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# Eval("WorkOrderKey", "<%$ AppSettings:DispatchLink %>") %>'
Text='<%# Eval("WorkOrderKey") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
The problem is right after "AppSettings:DispatchLink", it closes the tag when it see "%>". Is there a way around this problem?
Thank you,
Kenny.
You cannot nest <%# and other tags. Use ConfigurationManager.AppSettings["DispatchLink"] (pls. lookup correkt Class/Property in MSDN) instead.
Or: If your are using that HyperLink Control more than once I would suggest that you create an own MYHyperLink derived from System.Web.UI.WebControls.HyperLink and set the Property NavigateUrlFormatString in your Constructor.
Something like this:
public class DispatchLink : System.Web.UI.WebControls.HyperLink
{
public DispatchLink()
{
this. NavigateUrlFormatString = ConfigurationManager.AppSettings["DispatchLink"]
}
}

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