Error executing code in html style attribute - c#

I am receiving an error when I try to execute code in a style attribute as followed
<asp:LinkButton ID="lnkActivate" style='<%#Convert.ToBoolean(Eval("Activate")) ? "text-decoration:none;display:none;" : "text-decoration:none;display:block;"%>' runat ="server" CommandArgument='<%# Eval("ID") %>' OnClientClick ='return confirm("You want to send email to user to activate his account?");' CommandName ="activate" Text="Send Email" ></asp:LinkButton>
The error being thrown back is:
Error: Unexpected '<' in tag 'asp:LinkButton'.
I'm sorry if this question does not meet the community standards.
The code is also in C#
Edit:
Here is some more markup
<asp:Repeater ID="rpHostUsersList" runat="server" >
<ItemTemplate>
<tr class="odd gradeC" >
<td><%#DataBinder.Eval(Container.DataItem, "AccountID")%></td>
<td><%#DataBinder.Eval(Container.DataItem, "EmailAddress")%></td>
<td><%#DataBinder.Eval(Container.DataItem, "FirstName")%>, <%#DataBinder.Eval(Container.DataItem, "LastName")%></td>
<td><%#DataBinder.Eval(Container.DataItem, "Phone")%></td>
<td><%#DataBinder.Eval(Container.DataItem, "Address1")%></td>
<td><%#DataBinder.Eval(Container.DataItem, "City")%></td>
<td><%#DataBinder.Eval(Container.DataItem, "State")%></td>
<td><%#DataBinder.Eval(Container.DataItem, "Zip1")%></td>
<td>
<%#Convert.ToBoolean(Eval("Active")) ? "Yes" : "No"%>
</td>
<td> <%#Convert.ToBoolean(Eval("Activate")) ? "Yes" : "No"%>
<asp:LinkButton ID="lnkActivate" style='<%#Convert.ToBoolean(Eval("Activate")) ? "text-decoration:none;display:none;" : "text-decoration:none;display:block;"%>' runat ="server" CommandArgument='<%# Eval("ID") %>' OnClientClick ='return confirm("You want to send email to user to activate his account?");' CommandName ="activate" Text="Send Email" ></asp:LinkButton>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>

EDIT
Ok, your problem is related to Style Property of your LinkButton, which is read only
public CssStyleCollection Style { get; }
But you can use the CssClass property
public virtual string CssClass { get; set; }
So you can do something like this:
Define you style tag outside your control:
<style>
.myclassBlock{
text-decoration:none;
display: block
.myclassNone{
text-decoration:none;
display:none;
}
</style>
But if you apply your conditional logic inside your Linkbutton markup:
<asp:LinkButton ID="lnkActivate" CssClass='<%#Convert.ToBoolean(Eval("Activate")) ? "myclassBlock" : "myclassNone"%>' runat ="server" CommandArgument='<%# Eval("ID") %>' OnClientClick ='return confirm("You want to send email to user to activate his account?");' CommandName ="activate" Text="Send Email" ></asp:LinkButton>
In your output you will see this:
<a onclick="return confirm("You want to send email to user to activate his account?");" id="lnkActivate" class="<%#Convert.ToBoolean(Eval("Activate")) ? "myclassBlock" : "myclassNone"%>" href="javascript:__doPostBack('lnkActivate','')">Send Email</a>
Because '<%#Convert.ToBoolean(Eval("Activate")) ? "myclassBlock" : "myclassNone"%>', is not scriptlet, and will be output as plain text.
So you have to do something like this:
I have semplified your LinkButton:
<form>
<asp:Repeater ID="rpHostUsersList" runat="server" OnItemDataBound="rpHostUsersList_OnItemDataBound">
<HeaderTemplate>
<table border="1">
<tr>
<td><b>Activate</b></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Convert.ToBoolean(Eval("Activate")) ? "Yes" : "No"%> <asp:LinkButton ID="lnkActivate" runat="server" Text="Send Email"></asp:LinkButton></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
In code behind I have create a Datatable on the fly just to have some fake data to bind:
protected void Page_Load(object sender, EventArgs e)
{
Activate = true;
var ds = new DataSet();
var dt = new DataTable();
dt.Columns.Add("Activate");
dt.Rows.Add(new object[] { true });
dt.Rows.Add(new object[] { false });
dt.Rows.Add(new object[] { true });
ds.Tables.Add(dt);
rpHostUsersList.DataSource = ds;
rpHostUsersList.DataBind();
}
So this is what you have to do to achieve your task:
protected void rpHostUsersList_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var currentData = ((System.Data.DataRowView)e.Item.DataItem)["Activate"];
var b = Convert.ToBoolean(currentData);
var btn = (LinkButton)e.Item.FindControl("lnkActivate");
btn.CssClass = b ? "myclassBlock" : "myclassNone";
}
}
OUTPUT

Related

Why is the change in an html input textbox not being detected in asp.net?

I have a repeater, one column of which contains a textbox on which is attached a JQuery datepicker along with an update button. So a user uses the datepicker to change the date, clicks update and it writes to the database.The original date and the record id are stored in hidden fields.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<tr>
<td>
<asp:HiddenField ID="hidThisID" Value='<%# Eval("orderID") %>' runat="server" />
<asp:HiddenField ID="hidPrevDueDate" Value='<%# Eval("Duebeforedate", "{0:dd/MM/yyyy}") %>' runat="server" />
<input type="text" class="form-control fc-datepicker duedateinput" style="width: 150px" value='<%# Eval("Duebeforedate", "{0:dd/MM/yyyy}") %>' runat="server" id="fccd" readonly />
<asp:LinkButton ID="btnDateUpdate" OnClick="btnDateUpdate_Click" CssClass="btn btn-primary btn-sm" runat="server" ToolTip="Approved"> Update </asp:LinkButton>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
which calls this function
protected void btnDateUpdate_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
HtmlInputText htmlDueDate = (HtmlInputText)item.FindControl("fccd");
HiddenField hidID = (HiddenField)item.FindControl("hidThisID");
HiddenField hidOldDate = (HiddenField)item.FindControl("hidPrevDueDate");
DateTime prevDueDate = Convert.ToDateTime(hidOldDate.Value.ToString());
DateTime newDueDate = Convert.ToDateTime(htmlDueDate.Value.ToString());
string ID = hidID.Value;
if (prevDueDate != newDueDate)
{
string query = "update [tblOrders] set Duebeforedate=CONVERT(datetime,'" + newDueDate.ToString() + "', 103) where [orderID] = '" + ID + "'";
//database stuff here
}
}
}
However, the newDueDate variable still holds the original due date. Consequently the old and new dates match and so the database doesn't get updated. How do I get it to store the new value?
For two-way data binding you need to use the Bind keyword instead of Eval
Fixed it, it wasn't the btnUpdate function at all, I'd forgotten this check -
if (!IsPostBack)
{
//bind the repeater
}

How to get hidden field value in a html button in code behind in asp.net

I have created an HTML table with a repeater. In this table, I added a button column. It is an HTML button because ASP buttons not working inside of the tag. Therefore, I added an ASP hidden field inside of this HTML button to get selected row ID. I tried several ways to get the ID from the hidden field. I want to get selected row ID when the button click.
I have tried followings
I have tried this code but shows error in SendValueToSender(id); line. SendValueToSender is shown in red line using suggestions It generated method. But when I run the code and click the button shows error.
button_edit_ServerClick
protected void button_edit_ServerClick(object sender, EventArgs e)
{
try
{
var btn = (HtmlButton)sender;
var child = btn.FindControl("hidden");
string id = Convert.ToString(((HiddenField)child).Value);
SendValueToSender(id);
Response.Write("id" + id);
}
catch (Exception exception)
{
Response.Write(exception);
}
}
Generated method for SendValueToSender
private void SendValueToSender(string id)
{
throw new NotImplementedException();
}
Error-After add SendValueToSender method
System.NotImplementedException: The method or operation is not implemented. at EasyTravel.Manage.ManageNode.SendValueToSender(String id) in C:\Users\kularathna\source\repos\EasyTravel\EasyTravel\Manage\ManageNode.aspx.cs:line 241 at EasyTravel.Manage.ManageNode.button_edit_ServerClick(Object sender, EventArgs e) in C:\Users\kularathna\source\repos\EasyTravel\EasyTravel\Manage\ManageNode.aspx.cs:line 229
229 - SendValueToSender(id);
241 - throw new NotImplementedException();
PageLoad Method
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create Database Connection
SqlConnection con = new SqlConnection("Data Source= LAPTOP-J70EHC58 ; Initial Catalog= Bus_Management_System ; Integrated Security = True ; Connect Timeout = 30 ; ");
con.Open();
//Retrieve node details
string sqlst = "SELECT * FROM Node ";
SqlDataAdapter sqlData = new SqlDataAdapter(sqlst, con);
DataTable dt = new DataTable();
sqlData.Fill(dt);
rptrNode.DataSource = dt;
rptrNode.DataBind();
}
}
ManageNode.aspx
<table id="datatable-buttons" class="table table-striped table-bordered">
<thead>
<tr>
<th>Node_ID</th>
<th>Node_Name</th>
<th>Starting_Node</th>
<th>Ending_Node</th>
<th>Distance_Between_Nodes</th>
<th>Ticket_Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<asp:Repeater ID="rptrNode" runat="server">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblNodeID" runat="server" Text='<%# Eval("Node_ID") %>'></asp:Label></td>
<td>
<asp:Label ID="lblNodeName" runat="server" Text='<%# Eval("Node_Name") %>'></asp:Label></td>
<td>
<asp:Label ID="lblStartingNode" runat="server" Text='<%# Eval("Starting_Node") %>'></asp:Label></td>
<td>
<asp:Label ID="lblEndingNode" runat="server" Text='<%# Eval("Ending_Node") %>'></asp:Label></td>
<td>
<asp:Label ID="lblDistance" runat="server" Text='<%# Eval("Distance_Between_Nodes") %>'></asp:Label></td>
<td>
<asp:Label ID="lblTicketPrice" runat="server" Text='<%# Eval("Ticket_Price") %>'></asp:Label></td>
<td>
<button runat="server" clientidmode="Static" class="btn btn-success" id="button_edit" onserverclick="button_edit_ServerClick">
<asp:HiddenField runat="server" ID="hidden" Value='<%#Eval("Node_ID") %>' />
Edit
</button>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</tbody>
</table>
Button Column(It is in above ManageNode.aspx)
<td>
<button runat="server" clientidmode="Static" class="btn btn-success" id="button_edit" onserverclick="button_edit_ServerClick">
<asp:HiddenField runat="server" ID="hidden" Value='<%#Eval("Node_ID") %>' />
Edit
</button>
</td>
In Design part, Load Jquery Js and Page Js.
<td>
<button runat="server" clientidmode="Static" class="btn btn-success"
id="button_edit" onclick="func('<%#Eval("Node_ID") %>')">
Edit
</button>
</td>
In Page Js:
$(document).ready(function(){
//button Click Function.
function func(Id){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../ManageNode.aspx/SendValueToSender",
data: "{ID: '" + Id + "'}",
dataType: "json",
success: function (data) {
var tdata = jQuery.parseJSON(data.d);
},
error: function (result) {
alert('Data not found.');
}
});
}
});
In Server side.
[WebMethod]
public static void SendValueToSender(string ID)
{
//do your stuff.
}

How to find control in ListView on Page Load

I am trying to find the formview inside my listview on the page load. However, my result is always null. I called the DataBind method first but still nothing.
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
String list = itemdropdownlist.SelectedValue;
switch (list)
{
case "Section Item":
SectionListView.DataBind();
//SectionListView.Enabled = false;
var temp = (FormView)SectionListView.FindControl("SectionFormView");
temp.Enabled = true;
renderView(SectionListView, "hidden"); // hide listview on page load
break;
}
}
ASP.net code
<InsertItemTemplate>
<tr style="">
<td>
<div style="font-size: .8em;">
<asp:FormView ID="SectionFormView" runat="server" DataKeyNames="SectionItemID" DataSourceID="SectionDataSource">
<ItemTemplate>
<asp:Button ID="InsertButton" runat="server" Text="Insert" OnClick="SectionItemButton_Click" Font-Size="1.2em" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" Font-Size="1.2em" />
<asp:Label ID="SectionItemLabel" runat="server" Text="SectionItem" Font-Bold="true" Font-Size="1.2em" />
<asp:TextBox ID="SectionItemTextBox" runat="server" />
<asp:Label ID="SectionItemSubLabel" runat="server" Text="SectionItem Label" Font-Bold="true" Font-Size="1.2em" />
<asp:TextBox ID="SectionItemLabelTextBox" runat="server" />
</ItemTemplate>
</asp:FormView>
</div>
</td>
</tr>
</InsertItemTemplate>
<ItemTemplate>
You got that error, because the listview was not binded yet, so i think the best way would be to do all this on the ItemDataBound event. You would find the FormView like:
if (e.Item.ItemType == ListViewItemType.DataItem)
{
FormView SFormView= (FormView)e.Item.FindControl("SectionFormView");
if (SFormView!= null)
{
//code here
}
}
You could use this code to find about anything. I used it before to find Literals that I created in code behind. Use this code to find your FormView
private readonly List<FormView> _foundControls = new List<FormView>();
public IEnumerable<FormView> FoundControls
{
get { return _foundControls; }
}
public void FindChildControlsRecursive(Control control)
{
foreach (Control childControl in control.Controls)
{
if (childControl.GetType() == typeof(FormView))
{
_foundControls.Add((FormView)childControl);
}
else
{
FindChildControlsRecursive(childControl);
}
}
}
FindChildControlsRecursive(<Insert relevent Code Here: Whatever element you want to search inside of like your listView, find that using FindControl>);
FormView[] strControl = new FormView[200];
strControl = FoundControls.ToArray();
foreach (FormView i in strControl)
{
if (i.ID.Equals("< insert controlId of your FormView>"))
{
// do something when you find it
}
}

How do I programmatically change the color behind a pager or repeaters select page number?

I'm a rookie attempting to build an e-commerce site. My pager control that I use to display page numbers uses a repeater, which looks pretty dull. Can anyone show me how to programmatically change the background color of the page number that the user has selected? Or programmatically connect it to a CSS style sheet block of code that does it. Example: change the color behind the number to an orange square with a black border around it. Thanks.
Current code :
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Pager.ascx.cs" Inherits="UserControls_Pager" %>
<p> Page <asp:Label ID="currentPageLabel" runat="server" />
of <asp:Label ID="howManyPagesLabel" runat="server" /> |
<asp:HyperLink ID="previousLink" Runat="server">Previous</asp:HyperLink>
<asp:Repeater ID="pagesRepeater" runat="server">
<ItemTemplate>
<asp:HyperLink ID="hyperlink" runat="server" Text='<%# Eval("Page") %>'
NavigateUrl='<%# Eval("Url") %>' />
</ItemTemplate>
</asp:Repeater>
<asp:HyperLink ID="nextLink" Runat="server">Next</asp:HyperLink>
</p>
UserControl ASPX:
<p> Page <asp:Label ID="currentPageLabel" runat="server" /> of
<asp:Label ID="howManyPagesLabel" runat="server" /> |
<asp:HyperLink ID="previousLink" Runat="server">Previous</asp:HyperLink>
<asp:Repeater ID="pagesRepeater" runat="server"
onitemdatabound="pagesRepeater_ItemDataBound"> <ItemTemplate>
<asp:HyperLink ID="hyperlink" runat="server" Text='<%# Eval("Page") %>'
NavigateUrl='<%# Eval("Url") %>' /> </ItemTemplate>
</asp:Repeater>
<asp:HyperLink ID="nextLink" Runat="server">Next</asp:HyperLink> </p>
UserControl Code behind:
public class p
{
public string Page { get; set; }
public string Url { get; set; }
public p(string url, string page)
{
Page = page;
Url = url;
}
}
protected void Page_Load(object sender, EventArgs e)
{
List<p> arr = new List<p>();
arr.Add(new p("a.aspx", "a"));
arr.Add(new p("b.aspx", "b"));
pagesRepeater.DataSource = arr;
pagesRepeater.DataBind();
}
protected void pagesRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
HyperLink lnk = (HyperLink)e.Item.FindControl("hyperlink");
string[] URL = Request.Url.Segments;
string currentUrl = URL[URL.Length - 1];
if (lnk != null)
{
string lnkUrl=lnk.NavigateUrl;
if (lnkUrl == currentUrl)
{
lnk.BackColor = Color.Orange;
lnk.Style.Add("border", "1px solid #000000");
lnk.Style.Add("background-color", "orange");
lnk.Style.Add("text-decoration", "none");
}
}
}
You can do that through client side Jquery, for an example if your control that you want to color has an ID "MyControl"
$("#MyControl").css( "color", "red" ),
you don't have to change it from code behind.
Call this code in the document ready of your page as following:
<script>
$(document).ready(function() {
$("#MyControl").css( "color", "red" )
});
</script>
remember its always better to put your script code at the end of the page as it makes your page run faster.

Repeater in ASP.net

I used repeater in asp.net. My problem is don't know how to hide a fields in repeater. There is a regular price and now price if regular price is equal to zero it will hide the fields and if not it will show the value of the regular price. i hope you can help on this.
here my code in asp:
<a href="<%=Utility.GetSiteRoot() %>/BookInfo.aspx?SKU=<%# Utility.SKUMask(Eval("lb_sku").ToString()) %>">
<img width="150px" src='<%# Eval("lb_picturepath")%>'>
</td>
<td valign="top">
<asp:Label ID="lb_titleLabel" runat="server" CssClass="center-head" Text='<%# Eval("lb_title") %>' />
<p><asp:Label ID="lb_descriptionLabel" runat="server" Text='<%# Eval("lb_description") %>' /></p>
<div class="price"><%# "Price: " + decimal.Round((decimal)Eval("lb_sellingprice"),2)%></div>
</td>
</tr>
<tr>
<td></td>
<td>
<a class="addtocart" href="<%=Utility.GetSiteRoot() %>/AddToCart.aspx?SKU=<%# Utility.SKUMask(Eval("lb_sku").ToString()) %>" >Add To Cart</a>
<a href="<%=Utility.GetSiteRoot() %>/BookInfo.aspx?SKU=<%# Utility.SKUMask(Eval("lb_sku").ToString()) %>" class="readmore">
View Details
</a></td>
thanks!
You would need to handle the OnItemDataBound event, and then change the visibility of the control. An example of this is shown below:
ASPX Page
<asp:Repeater ID="MyRepeater" OnItemDataBound="MyRepeater_OnItemDataBound" runat="server">
<ItemTemplate>
<asp:Label ID="RegularPriceLabel" runat="server" />
<br/>
<asp:Label ID="BuyNowPriceLabel" runat="server" />
</ItemTemplate>
</asp:Repeater>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyRepeater.DataSource = GetDataSource();
MyRepeater.DataBind();
}
}
protected void MyRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// This will be your data object
MyEntity o = (MyEntity) e.Item.DataItem;
// Get the labels
Label RegularPriceLabel = (Label) e.Item.FindControl("RegularPriceLabel");
Label BuyNowPriceLabel = (Label) e.Item.FindControl("BuyNowPriceLabel");
// Only show regular price if it is set
RegularPriceLabel.Visible = (o.RegularPrice > 0);
// Populate labels
RegularPriceLabel.Text = o.RegularPrice.ToString();
BuyNowPriceLabel.Text = o.BuyNowPrice.ToString();
}
}
I would take a look at the ItemDataBound event of the Repeater. It will fire for every item in the repeater and allow you to do any code-behind (like hiding labels) more easily.
Edit: For your specific example, since you are formatting the price as well, it may be easier to just call a custom method to to render the price, like so:
ASPX:
<%#RenderPrice((decimal)Eval("lb_sellingprice"))%>
Method:
protected string RenderPrice(decimal price) {
if (price > 0) {
return "Price: $" + decimal.Round(price);
} else {
return string.Empty;
}
}
It's quick-and-dirty but it works.

Categories

Resources