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
Related
Lets preface this with the fact that I am learning ASP.NET C# and this is my first "real" project so there is a good chance I am missing something obvious, I apologize in advance.
I am working on a web page that displays three columns. The first is "Categories", a user should be able to select a category then have a list of items to choose from appear in the second column "Items". When they click an item the third column should show details about said item. For the most part this is a classic Master/Detail scenario except we take it a step further and do Master/Detail/Detail.
To achieve this I am generating dynamic buttons on Page_Load() in the "Categories" column. In addition I have added a debug line when the page loads, this is important later.
protected void Page_Load(object sender, EventArgs e)
{
//DB query to get categories omitted
for (int i = 0; i < categories.Rows.Count; i++)
{
Button btn = new Button();
btn.Click += new System.EventHandler(CategorySelected_Click);
btn.Attributes["runat"] = "server";
btn.ID = "CatSelBtn" + i;
btn.Attributes["data-categoryid"] = qry.GetCategories().Rows[i]["id"].ToString();
//And some other non-relevant attributes
CategoriesPane.Controls.Add(btn);
}
System.Diagnostics.Debug.WriteLine("Page Loaded");
}
As you may have noticed these buttons have a Click event handler that calls the method CategorySelected_Click(). These buttons all generate successfully and clicking on them results in that method being successfully called. This method is set up in a similar fashion, it grabs a list of items then generates buttons for the items, of course this needs to be done asynchronously so it doesn't reset the user's category selection, so this time it is all contained with an update panel.
C#
protected void CategorySelected_Click(object sender, EventArgs e)
{
//DB query to get items omitted
Button btn = (sender as Button);
string categoryid = btn.Attributes["data-categoryid"].ToString();
for (int i = 0; i < items.Rows.Count; i++)
{
if (items.Rows[i]["Category"].ToString() == categoryid)
{
Button ibtn = new Button();
ibtn.Click += new System.EventHandler(this.ItemSelected_Click);
ibtn.Attributes["runat"] = "server";
ibtn.ID = "ItmSelBtn" + i;
ibtn.Attributes["data-itemid"] = qry.GetItems().Rows[i]["id"].ToString();
//And again some none relevant attributes here
ItemsParent.Controls.Add(ibtn);
}
}
ItemsPanel.Update();
}
ASP
<div class="col-md-2 items-pane">
<asp:UpdatePanel ID="ItemsPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">
<ContentTemplate>
<div id="ItemsParent" runat="server">
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="col-md-8 view-pane">
<asp:UpdatePanel ID="ItemDetailsPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">
<ContentTemplate>
<div id="ItemDetailsParent" runat="server">
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
Again this generates a list of buttons for each item matching the correct category. No issue there, but this time I need the clicked button to call the third and final method which will display the details for the item. This is where things stop working. I assumed that because I was able to generate buttons successfully on Page_Load() that it would work the same inside an update panel. Right now the third method just contains a debug line to check if its firing at all.
protected void ItemSelected_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Item has been selected");
ItemDetailsPanel.Update();
}
In my output console in visual studio when I click on an Item Button control it writes Page Loaded indicating a successful postback but I am not seeing Item has been selected indicating that the third method is firing. I also inserted a breakpoint there but it is not being reached.
I initially thought I needed to add an asyncpostback trigger for each button generated to my update panel but that did not seem to resolve that issue, and because I can now see that Page_Load() is getting triggered I am pretty sure that isn't the issue. This leads me to believe that the click event is somehow not being registered. So my question to you is this: How do I make a dynamically generated button inside an update panel call a server side method? Any help is greatly appreciated.
You need to attach the event handlers on every postback.
It works for your categories-buttons, because the attaching is executed on every page load.
Do this for all the other items also, e.g. put in your Page_Load something like this:
foreach (var ctrl in ItemsParent.Controls)
{
Button ibtn = ctrl as Button;
if (ibtn != null)
{
ibtn.Click += new System.EventHandler(this.ItemSelected_Click);
}
}
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";
}
I need to be able to change the value of a TextBox(s) in a GridView template field from a TextChanged event. So the user can enter some text in a TextBox outside of the Gridview and then the TextBox(s) in the GridView gets updated to what the user entered.
This is what I need to do:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
template_text_box1.Text( in template field ) = TextBox1.Text << (TextBox1)( outside of gridview )
}
I have tried FindControl. This needs to happen without using any of the GridView events. I am just stumped. Could someone point me in the right direction? Maybe some JavaScript?
I believe that you would want to define a separate TextBox for the display and do something like the following:
double value1;
private void template textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if textBox1.Text (Double.TryParse(textBox1.Text, out value1))
{
textBox15 = value1.ToString();
}
}
This way you can make your other TextBox outside the grid and be able to call it and set to the value that is inputted.
On the .Aspx page, in the GridView column template TextBox add a CSS class.
<asp:TextBox ID="TextBox1" runat="server" CssClass="box-to-change" Text=""></asp:TextBox>
Also on the .Aspx page add a JavaScript function that uses jQuery:
<script type="text/javascript">
function updateAllTextboxes(value)
{
$('input.box-to-change').val(value);
}
</script>
In the code-behind add the JavaScript function as a client OnChange event (will not require PostBack).
otherTextBox.Attributes["onchange"] = "updateAllTextboxes(this.value)";
IpInterfaceUC UserControl
<div id="dvChannel" runat="server">
<asp:GridView ID="gvChannelUC"
OnRowCommand="gvChannelUC_RowCommand"
OnSelectedIndexChanged="gvChannel_SelectedIndexChanged"
/>
</div>
IPServices page CodeBehind
if (!IsPostBack){
}else
{
string str_btn = Request.Form.Keys[Request.Form.Keys.Count - 1].ToString();
handleClick(str_btn);
}
Question
It always show str_btn is null.If I click Button,It'll show button's id.But when I click Select at GridView,It show str_btn is null.It should be show GridView's id when we click select.
Thanks for any explain.
Try giving name attribute to your gridview,ie name="yourGridName".
<div id="dvChannel" runat="server" name="yourGridName">
<asp:GridView ID="gvChannelUC" name="yourGridName"
OnRowCommand="gvChannelUC_RowCommand"
OnSelectedIndexChanged="gvChannel_SelectedIndexChanged"
/>
</div>
As per my understanding you need grid event handing (.ascx) on page/codebehind (.aspx).
declare eventhandler in userControl
public event EventHandler<EventArgs> RaiseSelectedIndexChanged=delegate {};
handle userControl selectedindexchanged event in userControl.cs
protected void gvChannel_SelectedIndexChanged(object sender, EventArgs e)
{
var raiseSelectedIndexChanged = RaiseSelectedIndexChanged ;
if(raiseSelectedIndexChanged!=null)
{
raiseSelectedIndexChanged(sender, e);
}
}
register and use your userControl in aspx (which I hope you already did) this code will go in aspx page
<uc:userControl OnRaiseSelectedIndexChanged="OnRaiseSelectedIndexChanged"/>
handle the event in aspx code behind
protected void OnRaiseSelectedIndexChanged(object sender, EventArgs e)
{
//handle your event and put logic
}
I hope i make it clear , let me know if it confuses you.
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>