Pass an asp web control as a CommandArgument - c#

In my web app I have a series of ImageButtons. Upon clicking any of these ImageButtons, the ImageButton that was clicked needs to have it's image changed.
I would like one OnClick method that performs its action on the ImageButton that was clicked. Here is my attempt so far:
ASP.NET Code:
<asp:ImageButton ID="ImageToChange1" runat="server" OnClick="ChangeImage" CommandArgument="ImageToChange1"/>
<asp:ImageButton ID="ImageToChange2" runat="server" OnClick="ChangeImage" CommandArgument="ImageToChange2"/>
<asp:ImageButton ID="ImageToChange3" runat="server" OnClick="ChangeImage" CommandArgument ="ImageToChange3"/>
For my C# Code I want to do something like the following:
public void ChangeImage(object sender, CommandEventArgs e)
{
e.CommandArgument.ImageUrl = "~/Images/Penguins.jpg";
}
I'm wondering if there is a more appropriate way to do this than using the "OnClick" event or if I can accomplish this by manipulating "e" or "sender" somehow. Any insight would be greatly appreciated. Thank you.

In your ChangeImage, you can get the CommandArgument and the control as below
public void ChangeImage(object sender, CommandEventArgs e)
{
ImageButton imageButton = sender as ImageButton;
string imageToChange = e.CommandArgument;
//Then you can assign the appropreate image
imageButton.ImageUrl = "~/Images/Penguins.jpg";
}

Related

Which link is clicked in asp.net gridview row

I am adding two links and some plain text in same cell of gridview, I also have gridview_SelectedIndexChanged function which is called when any of the link is clicked and based of the value from grid I am running my db queries. gridview is also created dynamically so can have different number of rows.
Is there a way to know Link1 or Link2 is clicked in gridview_SelectedIndexChanged function?
protected void gridview_SelectedIndexChanged(object sender, EventArgs e)
{
if (Link1.Clicked)
{do this}
elseif (Link2.Clicked)
{do this}
}
You would want to track which link is clicked by using an ASP.NET control
<asp:LinkButton ID="Link1" runat="server" Click="Link1_Click" />
in your html
Then add an event handler in your backend like
public void Link1_Click(object sender, EventArgs e)
{
//add variable marking this link was clicked
link1_clicked = true;
Response.Redirect("Link1Destination.aspx");
}
and do the same for link2
<asp:LinkButton ID="Link2" runat="server" Click="Link2_Click" />
public void Link2_Click(object sender, EventArgs e)
{
//add variable marking this link was clicked
link2_clicked = true;
Response.Redirect("Link2Destination.aspx");
}
Add the boolean variables link1_clicked and link2_clicked to the top of you backend code. Then when you need to check what has been clicked you can filter though your boolean variables to see what is marked true as clicked with a for-loop.
Basically the Event handlers are your if clicked statements.

Session in not passed between pages c#

I'm working with VS 2013 and Mysql, in one of my pages I put select query in a gridview in this view and I have a button for each row so that if I press a row button I have a new window opening that has the colum Id (which is the first colum ) from the gridview.
the grid view button code:
<Columns>
<asp:TemplateField ><ItemTemplate><asp:Button ID="gridbutton" runat="server" Text="Plus de détails" OnClientClick="basicPopup();return false;" RowIndex='<%# Container.DisplayIndex %>' OnClick="button_click" /></ItemTemplate></asp:TemplateField>
</Columns>
the code of the button_click method:
protected void button_click(object sender, EventArgs e)
{
Button gridbutton = sender as Button;
int rowIndex = Convert.ToInt32(gridbutton.Attributes["RowIndex"]);
string n = "l'index" + rowIndex + "";
Session["idProjet"] = GridView1.Rows[rowIndex].Cells[2].Text;
//string idProjet = Convert.ToString(Session["idProjet"]);
// Alert.Show(idProjet);
}
I just used the two last lines to make sure that I'm getting the value, and I'm getting the right value.
And this is the code from the second page where I want to get the session value:
protected void Page_Load(object sender, EventArgs e)
{
string idProjet = Convert.ToString(Session["idProjet"]);
Alert.Show(idProjet);
}
But all I'm getting is an empty result.
In you button code you have both onclientclick and click event.
In you clickclick event I guest you are opening the different page. Note that client click executes first. So the new page already gets opened. Your server side event executes later. That is why the session is not available in the new form.
<asp:Button ID="gridbutton" runat="server" Text="Plus de détails" OnClientClick="basicPopup();return false;" RowIndex='<%# Container.DisplayIndex %>' OnClick="button_click" />
In this case you have to pass the idProject as query string to the new page.

Click Event of Dynamically generated Anchor Not Firing

I have an anchor on Lable Text.I am creating anchor with runat="server" dynamically on click of a button, It gets created as expected. I want to use its click event but it does not fire.
My code :
lblEmail.Text = email + " <a href='#' runat='server' class='crossicon' onclick='removebtn_Click'></a> ";
protected void removebtn_Click(object sender, EventArgs e)
{
}
How Can I create event for this button?I don't want to use JS, as in that case I will have to use a hidden field for new value
Adding markup/text to the label in that way wouldn't add the linkbutton or register the event to the control tree at the server. For that behavior of dynamically adding controls along with the server events to be achieved, you need to register the controls and events (as shown below)
aspx:
<asp:Panel runat="server" id="pnlEmail">
<asp:Label runat="server" id="lblEmail"/>
</asp:Panel>
aspx.cs:
In whichever event, you want to set the label text (along with the link)
lblEmail.Text = email;
LinkButton lnkbtnEmail = new LinkButton();
lnkbtn.Click += lnkbtn_Click;
lnkbtn.Text = "Dynamic Link";
pnlEmail.Controls.Add(lnkbtnEmail);
And the Handler would be
void lnkbtn_Click(object sender, EventArgs e)
{
// code for your dynamically generated link
}
By default, controls use __doPostBack to do the postback to the server. __doPostBack takes the UniqueID of the control (or in HTML, the name property of the HTML element). The second parameter is the name of the command to fire.
<a href='#' runat='server' class='crossicon' href="javascript:void(0);" onclick="__doPostBack('someuniqueid', '');></a>
System.Web.UI.Page already implements the IPostBackEventHandler interface by default, so you don't need to implement it on every page - it's already there.
You can override the RaisePostBackEvent method on the page like this:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
//call the RaisePostBack event
base.RaisePostBackEvent(source, eventArgument);
if (source == SomeControl)
{
//do something
}
}
I hope it will help you.
I don't think so it is created dynamically. Where is ID of that control. You have to Create Server side control and add it into some placeholder/panel e.t.c

Disable Postback on button ASP.NET c#

here is an example of what I am doing
Page Load
{
//Adds items to a panel (not an updatepanel just a normal panel control)
}
protected void btnNexMod_Click(object sender, EventArgs e)
{
// Calls DoWork() and Appends more items to the same panel
}
My problem is that the asp:button is doing a postback as well as calling DoWork()
Therefore, re-calling my page load, re-initializing my panel :(
I want my items that I have added to the panel to stay there!
All help appreciated, not looking for a hand you the answer kind-of deal. Any steps are appreciated thanks!
Here is an exact example of my problem.
protected void Page_Load(object sender, EventArgs e)
{
CheckBox chkbox = new CheckBox();
chkbox.Text = "hey";
chkbox.ID = "chk" + "hey";
// Add our checkbox to the panel
Panel1.Controls.Add(chkbox);
}
protected void Button1_Click(object sender, EventArgs e)
{
CheckBox chkbox = new CheckBox();
chkbox.Text = "hey";
chkbox.ID = "chk" + "hey";
// Add our checkbox to the panel
Panel1.Controls.Add(chkbox);
}
Only thing on the page is a empty panel and a button with this click even handler.
I have also tried this and it still doesn't work. Now its clearing the initial item appended to the panel.
if (!Page.IsPostBack) // to avoid reloading your control on postback
{
CheckBox chkbox = new CheckBox();
chkbox.Text = "Initial";
chkbox.ID = "chk" + "Initial";
// Add our checkbox to the panel
Panel1.Controls.Add(chkbox);
}
If you're adding controls to the Panel dynamically, then you'll have to recreate the controls at every postback, and make sure to assign the same IDs to the controls so that ViewState can populate the values. It's usually best to recreate dynamic content during OnInit, but this can be difficult in some situations.
One of my favorite tools is the DynamicControlsPlaceHolder, because you can add dynamic controls to it and it will persist them automagically, without any additional coding required on the page. Just add controls to it, and it will do the rest.
Here's the link:
http://www.denisbauer.com/Home/DynamicControlsPlaceholder
As for preventing your button from performing a postback, use OnClientClick and return false.
OnClientClick="return false;"
You could use
<asp:LinkButton OnClientClick="javascript:addItemsToPanel();return false;"
thus using a javascript function to add them. That's how I've got around that problem.
You can also try this:
Page Load
{
if (!this.IsPostBack) // to avoid reloading your control on postback
{
//Adds items to a panel (not an updatepanel just a normal panel control)
}
}
you can do like this...
ASPX code:
<asp:LinkButton ID="someID" runat="server" Text="clicky"></asp:LinkButton>
Code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
someID.Attributes.Add("onClick", "return false;");
}
}
What renders as HTML is:
<a onclick="return false;" id="someID" href="javascript:__doPostBack('someID','')">clicky</a>
You are correct, you will have to add the new items to the Panel after a PostBack. That is the nature of the .NET pipeline.
If you use a data bound control, like a Repeater, to display the panel contents, then the button click handler just needs to rebind the control and it will all work out correctly.
Changing the asp:Button to a asp:LinkButton solved my issue.
I think, it is better use the Ajax Update panel. And put your button in to that.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button1" />
</ContentTemplate>
</asp:UpdatePanel>

SharePoint - Passing Dataview Row Arguments to a C# function from ASP.net button

I've done this with a asp.net Gridview. but does anybody have any examples on how to pass row information from an asp.net button in SharePoint Dataview rows to an inline C# function?
the button Repeats as follows:
<asp:Button runat="server" Text="Delete" id="Delete{#ID}" OnClick="DeleteDoc()"/>
My function looks like this:
void DeleteDoc(object sender, EventArgs e) { }
}
I tried adding another parameter but get:
No overload for 'DeleteDoc' matches delegate 'System.EventHandler'
Try to change your method access modifier to protected and OnClick="DeleteDoc()" to OnClick="DeleteDoc".
Also i didn't managed to make it work with id="Delete{#ID}" so try without that to.
This worked on my test case
<asp:Button runat="server" Text="Delete"
OnClick="DeleteDoc"
CommandArgument='<%# Eval("ID")%>'/>
and
protected void DeleteDoc(object sender, EventArgs e)
{
Button b = sender as Button;
YourDeleteDocumentHelperMethod(b.CommandArgument);
}

Categories

Resources