C#/ASP.Net - ImageButton OnClick CodeBehind function - c#

I've got default.aspx/default.aspx.cs and other.cs where i "store" a bunch of functions.
In my default.aspx i've :
<asp:ImageButton ID="ImageButton1" CssClass="btn_img" ImageUrl="./images/1.png" runat="server" OnClick='<%# "setFunction(" +Eval("aGUID") +")" %>' />
in my default.aspx.cs
protected void setFunction(object sender, ImageClickEventArgs e)
{
string istr = e.ToString();
var iguid = new Guid(istr);
// this are classes/functions stored in other.cs
ManageFun mfun = new ManageFun();
mfun.setMM(iguid);
}
I though i was doing all right, but can't figure out what i'm doing wrong!
In matter of fact it does nothing!
Apreciate any help!
Thanks!

You can try this
<h3>ImageButton Sample</h3>
Click anywhere on the image.<br /><br />
<asp:ImageButton id="imagebutton1" runat="server"
AlternateText="ImageButton 1"
ImageAlign="left"
ImageUrl="images/pict.jpg"
OnClick="ImageButton_Click"/>
<br /><br />
<asp:label id="Label1" runat="server"/>
and C# code
public void ImageButton_Click(object sender, ImageClickEventArgs e)
{
Label1.Text = "You clicked the ImageButton control at the coordinates: (" +
e.X.ToString() + ", " + e.Y.ToString() + ")";
}
No need to write these <%#
Here is the reference Click

Basically asp:ImageButton with Onclick which will not call the server side code with Eval.
Edit:
You can directly call like this :
<asp:ImageButton ID="ImageButton1" CssClass="btn_img" ImageUrl="./images/1.png" runat="server" OnClick="setFunction" />
if you want to pass the parameter to that function you can assign the param to the CommandArguement as below
CommandArguement='<%# Eval("aGUID") %>'
in your SetFunction you can retrieve like this
string val = e.CommandArguement.ToString()

Related

How to open a link in a new tab using ASP Link Button Property?

I have a gridview with the Template and it contains a LinkButton. When I click the button I want to open a link in new tab
<Templates>
<Obout:GridTemplate runat="server" ID="tempCurrTask">
<Template>
<asp:LinkButton Text='<%# Container.DataItem["CurrentTask"] %>' ID="lnkbtnview2"
runat="server" Font-Underline="true" OnCommand="SELREC" CommandArgument='<%# Container.PageRecordIndex %>'></asp:LinkButton>
</Template>
</Obout:GridTemplate>
And the SELREC function is
protected void SELREC(object sender, CommandEventArgs e)
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
Hashtable dataItem = grvLeads.Rows[rowIndex].ToHashtable() as Hashtable;
string id = Convert.ToString(dataItem["iTask_id"]); //.Split('|');
string rowIndexid = id.ToString();
//+ "/" + e.CommandName.ToString();
//ScriptManager.RegisterStartupScript(this, typeof(string), "openWindow", "window.open('Task.aspx?TaskID=" + rowIndexid.Trim() + "', '_newtab','left = 10, top=10,scrollbars=Yes,resizable=yes,width=1100,height=580'); ", true);
Response.Redirect("Task.aspx?TaskID=" + rowIndexid.Trim());
}
This link opens in the same tab. I want it to open in new tab, So I changed the asp:LinkButton to asp:HyperLink tag but the SELREC function is not called properly. I want to do it using LinkButton and I don't know how to do it by using the link button. So please anybody help me with sample code.
Try this approach;
<asp:LinkButton runat="server" href='<%# "Task.aspx?TaskID=" + MethodtoGenerateTaskId(parameter) %>' target="_blank">LinkButton</asp:LinkButton>
You should define MethodtoGenerateTaskId(parameter) in c# codebehind. Take CommandArgument as a parameter to this method.
protected string MethodtoGenerateTaskId(string command_arg)
{
int rowIndex = int.Parse(command_arg.ToString());
Hashtable dataItem = grvLeads.Rows[rowIndex].ToHashtable() as Hashtable;
string id = Convert.ToString(dataItem["iTask_id"]); //.Split('|');
string rowIndexid = id.ToString();
return rowIndexid.Trim();
}
and in markup;
<asp:LinkButton runat="server" href='<%# "Task.aspx?TaskID=" + MethodtoGenerateTaskId(Container.PageRecordIndex.ToString()) %>' target="_blank">LinkButton</asp:LinkButton>
and if it works; pls mark it as answer...

how to get image url on click in repeater

i want to get image url on clicking the image from database in repeater
my database contains(id,url)
my repeater code is:
<asp:Repeater runat="server" ID="repeater" >
<ItemTemplate >
<asp:ImageButton runat="server" Width="200px" Height="200px" ImageUrl='<%#Eval("url") %>' OnCommand="Image_Click" CommandName="ImageClick" CommandArgument='<%#Eval("url") %>' />
</ItemTemplate>
</asp:Repeater>
my .cs code is
protected void Image_Click(object sender, CommandEventArgs e)
{
if (e.CommandName == "ImageClick")
{
string a=e.CommandArgument.tostring();
responce.write(a);
}
}
you can do in ImageClick
((ImageButton)sender).ImageUrl
to get the url of the clicked button
Cast sender to ImageButton and read its ImageUrl property.
Also, is there a reason you are using command instead of handling ImageButtons click event?
Both Vladimir and Guigui answers are prefer way of accessing URL of an image button.
If you also want ID value in addition to URL, you can store multiple values into CommandArgument separated by comma.
<asp:ImageButton runat="server"
ImageUrl='<%#Eval("url") %>'
OnCommand="Image_Command"
CommandName="ImageClick"
CommandArgument='<%# Eval("Id")%> + "," + Eval("url") %>' />
protected void Image_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "ImageClick")
{
string[] commandArgs = e.CommandArgument.ToString()
.Split(',');
string id = commandArgs[0];
string url = commandArgs[1];
}
}

Passing variables to usercontrol inside the listview (asp.net, c#)

I want to pass some dynamic information from the listview to UserControl, but I guess I'm missing something.
.aspx page:
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource"
DataKeyNames="id_Image">
<ItemTemplate>
<uc1:Info Name_Lbl='<%# Bind("Name") %>' Description_Lbl='<%# Bind("Description")%>' ID="info1" runat="server" />
</ItemTemplate>
</asp:ListView>
.ascx file:
Name:
<asp:Label ID="NameLabel" runat="server" />
Description:
<asp:Label ID="DescriptionLabel" runat="server" />
.ascx codebehind file:
public string Name_Lbl { get; set; }
public string Description_Lbl { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
NameLabel.Text = Name_Lbl;
DescriptionLabel.Text = Description_Lbl;
}
Everything is working fine if Im trying to get value from string text like:
<uc1:Info Name_Lbl="Name" Description_Lbl="Description" ID="info1" runat="server" />
But when I'm trying to get value from Datasource, the string values in usercontrol are "null"
Can anyone see what I'm doing wrong? Thanks, Jim Oak
DataBinding occurs a lot later in the Control Life cycle than Load.
You assign your text on Load, but your control only receives the text on DataBind
To fix this you can set your text OnPreRender. This occurs after DataBind
protected override void OnPreRender(EventArgs e)
{
NameLabel.Text = Name_Lbl;
DescriptionLabel.Text = Description_Lbl;
}
Everything looks fine in your code just check the code line:
<uc1:Info Name_Lbl='<%# Bind("Name") %>' Description_Lbl='<%# Bind("Description"%>' ID="info1" runat="server" />
You are missing the closing bracket ")" against Description_Lbl. It should be:
<uc1:Info Name_Lbl='<%# Bind("Name") %>' Description_Lbl='<%# Bind("Description")%>' ID="info1" runat="server" />

Set innerHTML in javascript and get from C#

I have two labels:
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
and I set innerHTML by javascript:
document.getElementById('Label1').innerHTML = position.lat();
document.getElementById('Label2').innerHTML = position.lng();
How I can get those labels values in codebehind? I try:
TextBox2.Text = Label1.Text;
UPDATE:I need to get pushpin location:
<artem:GoogleMap ID="GoogleMap1" runat="server"
EnableMapTypeControl="False" MapType="Roadmap" >
</artem:GoogleMap>
<artem:GoogleMarkers ID="GoogleMarkers1" runat="server"
TargetControlID="GoogleMap1" onclientpositionchanged="handlePositionChanged">
</artem:GoogleMarkers>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<script type="text/javascript">
var list = document.getElementById("Label1");
function handlePositionChanged(sender, e) {
printEvent("Position Changed", sender, e);
}
function printEvent(name, sender, e) {
var position = e.latLng || sender.markers[e.index].getPosition();
document.getElementById('Label1').innerHTML = position.lat();
document.getElementById('Label2').innerHTML = position.lng();
}
</script>
protected void Button1_Click(object sender, EventArgs e)
{
TextBox2.Text = Label1.Text;// return value: Label
}
You cannot access the value on server side. You will have to use a hidden field for that:
<asp:HiddenField ID="Hidden1" runat="server" />
The set the innerHtml value in the Hidden field by doing:
document.getElementById('<%= Hidden1.ClientID %>').value = position.lat();
You can then access it from server side by doing:
TextBox1.Text = Hidden1.Value;
You are not able to do that with the Label control as when the page is posted back the content of labels are not posted to the server. You would need to make use of an input control of sorts. Probably a hidden input would be your best bet.
Take a hidden field like below
<asp:HiddenField ID="hdnBody" ClientIDMode="Static" runat="server" />
Then set its value in Jquery like below
<script>
function GetEmailID() {
var bodyHtml = $("#editor").html();
$("#hdnBody").val(bodyHtml);
}
</script>
And in the code behind do this to get it
string body = hdnBody.Value;

Creating a query string when clicking on image (asp.net/c#)

My application is an image gallery and with a Repeater control i'm listing the thumbnails (that's in a separate folder, apart from the full scale images). When clicking on a thumbnail a full scale image should be shown in the Image control "fullSizeImage" and a query string should be created which (with a GET of the page) shows that specific image in full scale.
The code for the query string is done, but the problem is that I don't have a clue where to put it (the creation of the query), because the HyperLink control doesn't support event clicks. Is there a way to use for example Repeater ItemCommand, or how could I accomplish what I want here?
Thanks!
from default.aspx:
<asp:Image ID="fullSizeImage" runat="server" />
<asp:Repeater ID="ImageRepeater" runat="server" DataSourceID="" >
<ItemTemplate>
<asp:HyperLink ID="ImageHyperLink" NavigateUrl='<%# Eval("Name", "~/Images/{0}") %>' runat="server" CssClass="thumbnails" >
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Name", "~/Images/Thumbnails/{0}") %>' CssClass="thumbnail" />
</asp:HyperLink>
</ItemTemplate>
</asp:Repeater>
from code behind:
protected void Page_Load(object sender, EventArgs e) {
var directory = new DirectoryInfo(Gallery.PhysicalApplicationPath + "/Images");
var theFiles = directory.GetFiles();
ImageRepeater.DataSource = theFiles;
ImageRepeater.DataBind();
var dataName = Request.QueryString["name"];
fullSizeImage.ImageUrl = dataName;
}
the creation of the query string (that I don't know where to put):
string str = ImageUrl; <- the url of the clicked image
Response.Redirect("default.aspx?name=" + Server.UrlEncode(str);
This works with me
<asp:HyperLink ID="ImageHyperLink" NavigateUrl='<%# "~/default.aspx?name=" + Server.UrlEncode(Eval("Name","~/Images/{0}")) %>' runat="server" CssClass="thumbnails" >
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Name", "~/Images/Thumbnails/{0}") %>' CssClass="thumbnail" />
</asp:HyperLink>
In the code behind you can set up a method tied to the Repeater's ItemDataBound event. In that method you can retrieve the current file, find the HyperLink, and set the link's NavigateUrl to be the string you are generating. Something like the following:
ImageRepeater.ItemDataBound += new RepeaterItemEventHandler(ImageRepeater_ItemDataBound);
private void ImageRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
[File] f = (File)e.Item.DataItem;
HyperLink ImageHyperLink = (HyperLink)e.Item.FindControl("ImageHyperLink");
string str = f.ImageUrl;
ImageHyperLink.NavigateUrl = "default.aspx?name=" + Server.UrlEncode(str);
}

Categories

Resources