Reset ImageButton ImageUrl to default URL - c#

I've an ImageButton into a Repeater.
My ASP.NET code is:
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:ImageButton ID="img_sport" runat="server" CommandName='<%# Eval("IDSport") %>' CommandArgument='<%# Eval("SportName") %>' ImageUrl='<%# Eval("SportName","~/Images/{0}-trp.png") %>' OnCommand="img_sport_Click" />
</ItemTemplate>
</asp:Repeater>
From code behind I change the ImageUrl of selected/clicked image in this way:
[...]
ImageButton btn = (ImageButton)sender;
btn.ImageUrl = "/Images/" + sportName + "-trp-selected.png";
[...]
But, if I click on other images, I'll have two/three/four image shown as selected, so first of all, in my code behind, I would like to reset ImageUrl to default value, then I'll apply the new ImageUrl only to the selected/clicked ImageButton.
So, how can I reset all ImageUrl?

On Seeing your code, I guess you want to change the image when it is clicked so that user can identify that whether image is selected or not. If you want to achieve this, why don't you try JavaScript which can handle same thing without postback.
See below code sample with JavaScript function for the same:
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:ImageButton ID="img_sport" runat="server" ImageUrl='<%# Eval("SportName","~/Images/{0}-trp.png") %>' OnClientClick='<%# "return ManageSelection(this,\"" + Eval("SportName").ToString() + "\");"%>' />
</ItemTemplate>
</asp:Repeater>
<script type="text/javascript">
function ManageSelection(control, sportName) {
var selectedImage = '/Images/' + sportName + "-trp-selected.png";
$(control).attr('src', selectedImage);
return false;
}
</script>

Related

How to pass an Eval method through the attributes.add property?

I have a Gridview with all the rows as textboxes and one edit button in the last column. All the textboxes have an onclick property which calls a javascript method. Here is the HTML code of one of the textbox:
<asp:TextBox ID="txtLoginName" Onclick='<%# "pass(" + Eval("userid") + ");" %>'
Text='<%# Eval("LoginName")%>' runat="server"></asp:TextBox>
When a user clicks on the Edit button, the onclick property is removed and the button changes to Save. After making the changes, when a user clicks Save, I want to re-add the onclick property again. This is the code I have tried:
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
TextBox lstTxt = (TextBox)row.FindControl("txtLoginName");
if (btn.Text == "Edit")
{
lstTxt.Attributes.Remove("onclick");
btn.Text = "Save";
}
else
{
lstTxt.Attributes.Add("onclick", "<%# 'pass(" + Eval("userid") + ");' %>");
btn.Text = "Edit";
}
But its showing error
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control
How to pass that correctly?
You have to get the userid from sonmewhere else. You could store it for example in a HiddenField or invisible label and use e.Row.FindControl to get this control. Another approach is using the button's CommandArgument.
aspx:
<asp:Button ID="btnEdit" runat="server" CommandName="Edit" CommandArgument='<%# Eval("userid") %>'>
codebehind:
string userID = btn.CommandArgument.ToString();
lstTxt.Attributes.Add("onclick", "pass(" + userID + ");");
Here is the approach with a control like HiddenField:
<asp:TemplateField HeaderText="UserID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="HidUserID" Value='<%#Eval("userid") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
Now you can get it from codebehind via FindControl:
HiddenField hidUserID = (HiddenField)e.Row.FindControl("HidUserID");
string userID = hidUserID.Value;
You can use like this:
use it in grid view template field
<asp:TemplateField HeaderText="userid" Visible="false">
<ItemTemplate>
<asp:Label runat="server" id="lblUserid" style="display:none" Text='<%# Eval("UserID") %>' />
</ItemTemplate>
</asp:TemplateField>
find in code behind
GridViewRow row = (GridViewRow)btn.NamingContainer;
Label lbl = (TextBox)row.FindControl("lblUserid");
string userid=lblUserid.Text;
lstTxt.Attributes.Add("onclick", "<%# 'pass(" + userid + ");' %>");

Place session variable value in the Text of label in asp.net

I have some labels inside a DataList which are populated with text from as the DataList is binded with database. Now i want to place the value of Text of asp.net with Session variable.
<asp:DataList ID = "dl_cmt" runat="server">
<ItemStyle CssClass="coment" />
ItemTemplate>
<asp:Label ID="ll" runat="server" Text='<%# %>' />
<asp:Label ID="lblcmt" runat="server" Text='<%#Eval("ecomment")%>' />
<asp:Label ID="lblDate" style=" color:brown; font-family:Cursive; font-size:x-small; " runat="server" Text='<%#Eval("my_date","on {0}") %>' />
</ItemTemplate>
</asp:DataList>
I want to place the text of label ID="ll" with session["userid"]
You can get the value as follows
ll.Text = Session["userid"].ToString();
Another approach:
You can also hide the implementation details from the aspx code with a property
.cs file
public string userid { get { return Session["userid"]; } }
.aspx file
<asp:Label ID="ll" runat="server" Text='<%= userid %>' >
This will work.
<asp:Label ID="ll" runat="server" Text='<%#Session["yourvariable"]%>'/>

Make repeater row checkable

I have a ASP.NET repeater consists of image and label(wrap inside a div).
I want to make the repeater row work like a checkbox.
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<div class="divItem">
<asp:HiddenField ID="hfIID" runat="server" Value='<%# Eval("ID") %>' />
<asp:Image ID="imgItem" runat="server" ImageUrl='<%# Eval("ImageURL") %>' />
<asp:Label ID="lblName" runat="server" Text='<%# Eval("ItemName") %>'></asp:Label>
</div>
</ItemTemplate>
</asp:Repeater>
For example, the repeater have 10 items.
When a user select item 3 and item 5(similar like a checkbox) and press Save, I need to get the selected Item ID.
you will need to add some client side scripting with jquery.
Here's how to do it:
in your .aspx define repeater as :
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<div class="divItem" id='divItem<%# Eval("ID") %>'>
<asp:HiddenField ID="hfSelected" runat="server" />
<asp:HiddenField ID="hfIID" runat="server" Value='<%# Eval("ID") %>' />
<asp:Image ID="imgItem" runat="server" ImageUrl='<%# Eval("ImageURL") %>' />
<asp:Label ID="lblName" runat="server" Text='<%# Eval("ItemName") %>'></asp:Label>
</div>
</ItemTemplate>
</asp:Repeater>
and then add this javascript:
<script>
$(function () {
$('.divItem').click(function () {
var item = $(this);
item.toggleClass("divItemSelected"); //mark div as selected: set background color, etc...
var selector = "#" + item.attr("id") + " input[type='hidden'][id*='hfSelected']";
var selected = $(selector).val();
if (selected == "true") {
$(selector).val("false");
} else {
$(selector).val("true");
}
});
});
</script>
And then in code-behind on button click, you do this:
protected void OnSaveClick(object sender, EventArgs e)
{
foreach (RepeaterItem item in rpt.Items)
{
HiddenField hfSelected = item.FindControl("hfSelected") as HiddenField;
bool selected = false;
bool.TryParse(hfSelected.Value, out selected);
if (selected)
{
HiddenField hfIID = e.Item.FindControl("hfIID") as HiddenField;
int id = Convert.ToInt32(hfIID.Value);
// do appropriate action as needed.
}
}
}
Hope this helps!
Regards,
Uros

hide gridview hyperlink in visible property of source rather then code behind

Ive got a gridview with an itemtemplate that has a hyperlink control in it. I want to hide a hyperlink control if its item in the database returned null:
<ItemTemplate>
<asp:HyperLink ID="hlSugar" Visible=<% DataBinder.Eval(Container, "DataItem.CaseID")==null %> ToolTip="View the issue in SugarCRM." Target="_blank" runat="server" NavigateUrl='<%# "http://myPath&record=" + DataBinder.Eval(Container, "DataItem.CaseID") %>' Text="Issue"></asp:HyperLink>
</ItemTemplate>
Not sure on the syntax can I do
Visible = <% iif(databinder.eval(container, "dataItem.caseid")==null, false, true) %>
Not sure how to get the syntax correct. I basically want to check if my `DataItem.CaseID is null and hide this field if it is.
I ended up using this:
Visible='<%# Eval("SugarCaseID") != DBNull.Value %>'
visible='<%# Eval("dataItem.caseid") != null) %>'
Give this a shot
You can do this
bool ShowLink(obj data)
{
if(data!=null) {return true; } return false;
}
aspx:
<asp:HyperLink ID="hlSugar" Visible='<%# ShowLink(Eval("CaseID"))%>'
ToolTip="View the issue in SugarCRM." Target="_blank" runat="server"
NavigateUrl='<%# "http://myPath&record="
+ DataBinder.Eval(Container, "DataItem.CaseID") %>' Text="Issue">
</asp:HyperLink>
Use this
<asp:HyperLink ID="hlSugar" Visible='<%# Convert.ToBoolean(Eval("DataItem.CaseID").ToString() == "0") %>' ToolTip="View the issue in SugarCRM." Target="_blank" runat="server" NavigateUrl='<%# "http://myPath&record=" + DataBinder.Eval(Container, "DataItem.CaseID") %>' Text="Issue" />
REference:
Conditions within .aspx file for ListView ItemTemplate

How to use button in repeater control?

I am using asp.net 3.5 with c#.I want to invoke button click event inside repeater control.
<asp:Repeater ID="rptFriendsList"
runat="server"
onitemcommand="rptFriendsList_ItemCommand">
<ItemTemplate>
<asp:ImageButton ID="btnSave"
runat="server"
ImageUrl="~/Contents/Images/save_button.png"
CommandName="Schedule"
UseSubmitBehavior="False" />
</ItemTemplate>
</asp:Repeater>
but when i click to a button its giving an error
"Invalid postback or callback
argument. Event validation is enabled
using in
configuration or <%# Page
EnableEventValidation="true" %> in a
page. For security purposes, this
feature verifies that arguments to
postback or callback events originate
from the server control that
originally rendered them. If the data
is valid and expected, use the
ClientScriptManager.RegisterForEventValidation
method in order to register the
postback or callback data for
validation."
my purpose is to execute some code in button click which is placed inside the repeater.Please help me to solve this issue.Thanks in advance.
UseSubmitBehavior="False" this property you have used is not present with the image button have you over ridden imagebutton class and added this property.
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_OnItemCommand" DataSourceID="SqlDataSource1">
<ItemTemplate>
key1:
<asp:Label ID="key1Label" runat="server" Text='<%# Eval("key1") %>'></asp:Label><br />
key2:
<asp:Label ID="key2Label" runat="server" Text='<%# Eval("key2") %>'></asp:Label><br />
key3:
<asp:Label ID="key3Label" runat="server" Text='<%# Eval("key3") %>'></asp:Label><br />
<asp:TextBox ID="col1" runat="server" Text='<%# Eval("col1") %>'></asp:TextBox>
<asp:TextBox ID="col2" runat="server" Text='<%# Eval("col2") %>'></asp:TextBox>
<br />
<asp:linkbutton ID="Linkbutton1" commandname="Update" runat="server" text="Update" CommandArgument='<%# Eval("key1") +"|"+Eval("key2")+"|"+ Eval("key3") %>' />
<asp:linkbutton ID="Linkbutton2" commandname="Cancel" runat="server" text="Cancel" />
</ItemTemplate>
protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Update")
{
string col1 = ((TextBox)e.Item.FindControl("col1")).Text;
string col2 = ((TextBox)e.Item.FindControl("col2")).Text;
string allKeys = Convert.ToString(e.CommandArgument);
string[] arrKeys = new string[2];
char[] splitter = { '|' };
arrKeys = allKeys.Split(splitter);
SqlDataSource1.UpdateParameters["col1"].DefaultValue = col1;
SqlDataSource1.UpdateParameters["col2"].DefaultValue = col2;
SqlDataSource1.UpdateParameters["key1"].DefaultValue = arrKeys[0];
SqlDataSource1.UpdateParameters["key2"].DefaultValue = arrKeys[1];
SqlDataSource1.UpdateParameters["key3"].DefaultValue = arrKeys[2];
SqlDataSource1.Update();
Repeater1.DataBind();
}
}
This also happens when you have assigned the datasource and data bound your repeater in the OnLoad event rather than OnInit
I have used this bellow code and runs ok
use this bellow code in .aspx page
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<table>
<tr>
<th>
Edit
</th>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td align="center">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Use this in .cs Make the event Repeater1_ItemCommand
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "Edit":
// Do some stuff when the Edit button is clicked.
break;
// Other commands here.
default:
break;
}
}
You can't use button, because button create postback on click and also itemcommand of repeater called!
But, If you want to use asp:button instead of asp:linkbutton, you have to set UseSubmitBehavior property of button to false. its means, button dont make postback.
<asp:Button ID="btnAccept" runat="server" Text="Accept All" CssClass="vb-default vb-green vb-txt-light" CommandName="Accept" CommandArgument='<%# Eval("UserID") %>' UseSubmitBehavior="false" />
Set page EnableEventValidation="false".
if you're adding items server side, try to assign unique ID to each ImageButton

Categories

Resources