Server method not firing inside Listview LayoutTemplate - c#

I have a server method that I want to run from a link inside the LayoutTemplate of my ListView. I've found that it doesn't fire unless I move the link outside the LayoutTemplate. Is there any other way to run a Serverside event from an anchor or LinkButton inside of a LayoutTemplate? I thought about trying a link with a CommandName and capturing that inside of OnItemCommand but I don't know if that works inside of the LayoutTemplate.
My anchor inside the LayoutTemplate:
<a runat="server" id="proceedCheckout" OnServerClick="startCheckout">
The server method:
public void startCheckout(object sender, EventArgs e)
{....

I attempted to replicate your issue but with no luck. It seems to work for me. I have included my test mark-up and code so that you can see if you are missing something:
Markup
<asp:ListView ID="listView1" runat="server">
<LayoutTemplate>
<div>
<asp:LinkButton ID="linkButton1" runat="server" OnClick="LinkButton_Click" Text="Link Button"></asp:LinkButton>
</div>
<div runat="server" id="itemPlaceholder" />
</LayoutTemplate>
<ItemTemplate>
<div><%# Container.DataItem %></div>
</ItemTemplate>
</asp:ListView>
Code
protected void Page_Load(object sender, EventArgs e)
{
List<string> data = new List<string>();
data.Add("Item 1");
data.Add("Item 2");
data.Add("Item 3");
listView1.DataSource = data;
listView1.DataBind();
}
protected void LinkButton_Click(object sender, EventArgs e)
{
//...
}
Hope this helps.

Related

onclick not being fired in ListView

I have a button within the ItemTemplate of my ListView:
<asp:ListView ID="notificiationsList" runat="server">
<ItemTemplate>
<button type="submit" commandargument='<%# Eval("offerID") %>' onclick="Accept_Click" runat="server" >Accept</button>
</ItemTemplate>
</ListView>
Then I have a breakpoint in my code:
protected void Accept_Click(object sender, EventArgs e)
{
.... // breakpoint here
}
However when I debug the page does nothing and it doesn't reach the breakpoint for some reason?
Does anyone understand what I am doing wrong?
I'm not entirely sure how you are binding your ListView. I created the following code with a few tweaks to what you have above.
<asp:ListView ID="lvNotification" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lbAccept" runat="server" OnClick="Accept_Click" CommandArgument="test" Text="Accept" />
</ItemTemplate>
</asp:ListView>
Binding the ListView:
List<string> tL = new List<string>(){ "this", "and", "that"};
lvNotification.DataSource = tL;
lvNotification.DataBind();
And I reused your click code:
protected void Accept_Click(object sender, EventArgs e)
{
// breakpoint here
}
I was able to hit the breakpoint without issue.
I had the same issue and was a statement in the pageload that causes the ListView to be binded again.
This causes the initial event lost.
Check the Page_Load just to be sure :)
HTH,
Milton

ASP.NET Button OnClick within Repeater and LoginView

I'm developing a ASP.NET website with a C# backend. I'm having a problem with how to set an onclick event for buttons that are nested inside of both a loginview and a repeater. The code works fine for displaying all of the other data (anonymous view displays only an error message) but right now the buttons just redirect to the same page and remove the repeater and all contents, whereas they're supposed to run a specific delete function. The repeater, as it is right now, uses an alternatingitem template. If I remove the buttons from the nested controls, they work. I've tried this with buttons, linkbuttons, and imagebuttons. I'd rather use the latter, if possible. Is it possible to assign an Onclick to these buttons if they're nested like this? If not, what approach should I use?
<asp:LoginView ID="LoginLinksView" runat="server" EnableViewState="false">
<AnonymousTemplate>
<asp:Label ID="errorlabel" runat="server"></asp:Label>
</AnonymousTemplate>
<LoggedInTemplate>
<asp:Repeater id="Repeater" runat="server" >
<HeaderTemplate>
<table cellspacing="0" cellpadding="0">
<thead></thead>
</HeaderTemplate>
<ItemTemplate>
<tr class="Repeaterrow">
<!--Additional code here-->
<asp:ImageButton ID="delbutton" runat="server" ImageUrl=
"~/Images/delete.png" Onclick="DeleteOnClick"/>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr class="Repeaterrow">
<!--Additional code here-->
<asp:ImageButton ID="delbutton" runat="server" ImageUrl=
"~/Images/delete.png" Onclick="DeleteOnClick"/>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</LoggedInTemplate>
</asp:LoginView>
Here are the problems with your approach
1- The button issues postback as it should. But you need to put some CommandArgument with to identify "key" or which row you are processing it for.
2- Re Bind your Repeater with source. Below is the sample code for you.
protected void Page_Load(object sender, EventArgs e)
{
BindRepeater();
}
private void BindRepeater()
{
List<int> items = new List<int>();
for (int i = 0; i < 10; i++)
{
items.Add(i);
}
Repeater.DataSource = items;
Repeater.DataBind();
}
protected void DeleteOnClick(object sender, EventArgs e)
{
ImageButton delbutton = (sender as ImageButton);
//1- call your method with passing in delbutton.CommandArgument - it will give you key/ whatever you like
//2- Rebind the Repeater here and that will bind controls again...
BindRepeater();
}
protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
ImageButton delbutton = (sender as RepeaterItem).FindControl("delbutton") as ImageButton;
if (delbutton != null)
{
delbutton.CommandArgument = (sender as RepeaterItem).ItemIndex.ToString();
}
}
and ASPX Repeater definition would change to
Thanks,
Riz

CheckBox control in asp.net (C#)

I added a checkbox to my form.
When the checkbox is checked, some information (TextBox, Label etc.) should appear right under the checkbox.
How can I do this?
Code:
<asp:CheckBox ID="CheckBox1" runat="server"
oncheckedchanged="CheckBox1_CheckedChanged" />
C#:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
}
Don't forget autopostback = true
<asp:CheckBox ID="CheckBox1" runat="server" oncheckedchanged="CheckBox1_CheckedChanged" AutoPostBack="true" />
<asp:Panel runat="server" ID="panel1"></asp:Panel>
-
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
panel1.Controls.Add(new Label { Text = "Text goes here" });
}
This allows you to add any control you want.
Just add TextBox, Label etc. controls and make them invisible.
Then in the CheckBox1_CheckedChanged function make them visible.
This is done by setting the bool Visible property
<asp:CheckBox ID="CheckBox1" runat="server" oncheckedchanged="CheckBox1_CheckedChanged" />
<asp:TextBox ID="textBox" runat="server" Visible=false />
and
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
textBox.Visible = true;
}
Add a new literal control under your checkbox tags,
<asp:Literal id="lblMsg" runat="server"/>
then in your CheckBox1_CheckedChanged event to this:
lblMsg.Text = "Checked";
and yes set the AutoPostBack property of your checkbox to true
I would suggest doing this using javascript. Your users won't have to "postback" and the feeling on the application will be better, and you will reduce the server charge.
Using jQuery, you can use something like this:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$("#chk").onclick(function() {
$("#content").toggle();
});
});
</script>
<input type="Checkbox" id="chk"/>
<div id="content" style="display:none">
<asp:TextBox runat="Server" id="oneOfYourControls" />
</div>
jQuery is not mandatory... you can use standard simple getElementById().
The only drawback, is that you cannot dynamically build the content, but in most case it's a not actually a matter
In Checked Changed Event write your code like this:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
Label1.Text = "Text";
}

How to re-bind ListView on OnClick event of a button?

this seemed simple at first but I can't get it to work.
I have the following scenario:
<asp:ListView ID="CommentsListView" runat="server">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<UC:Comment runat="server" CommentItem="<%# CurrentComment %>" />
<br />
</ItemTemplate>
</asp:ListView>
<asp:TextBox ID="NewComment" runat="server" />
<asp:ImageButton ImageUrl="/images/ball.png" runat="server"
OnClick="SubmitComment" />
Code:
protected void Page_Load(object sender, EventArgs e)
{
RenderListView();
}
protected void RenderListView()
{
CommentsListView.DataSource = //Get the data source objects
CommentsListView.DataBind();
}
protected CommentObject CurrentComment
{
get { return (CommentObject)Page.GetDataItem(); }
}
protected void SubmitComment(object sender, ImageClickEventArgs e)
{
//code to submit comment
RenderListView();
}
basically, when I submit a comment, I want to see it in the ListView, but I don't. "MyControl" gets a null comment in the post-back, for all of the items (not just the new one).
Only after I refresh the page, I can see the new comment that I'v submitted. I can't however refresh the page every submit because this code is inside an UpdatePanel (the issue occurs without the UpdatePanel as well).
Any idea how to solve this?
I can't find any specifics on this, but I have a hunch the user control in your ItemTemplate is causing the issue. Can you remove it and see if it works?
I notice that you are calling RenderListView in both SubmitComment and PageLoad which I believe will cause it to fire twice when the button is clicked (with PageLoad firing first). It looks like the code you posted is simplified. Is it possible that there is something happening in the PageLoad which is sabotaging your SubmitComment steps?
I finally solved it, if anyone else may encounter this -
The solution was to avoid "<%#" and instead use the ItemDataBound event:
<asp:ListView ID="Comments" runat="server"
OnItemDataBound="CommentsItemDataBound">
and the method itself:
protected void CommentsItemDataBound(object sender, ListViewItemEventArgs e)
{
var commentItem = (Comment)(((ListViewDataItem)e.Item).DataItem);
var commentControl = (Comment)e.Item.FindControl("CommentControl");
commentControl.CommentItem = commentItem;
}
This way, the binding of each control works as expected.

Refreshing a Repeater control in an UpdatePanel with ASP.NET

I'm trying to code a page where you can post a comment without reloading the whole page. The comments are displayed using a Repeater control. The template looks like this:
<asp:UpdatePanel runat="server" ID="commentsUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<!-- Comments block -->
<div class="wrapper bloc content">
<h3><img src="img/comments.png" alt="Comments" /> Comments</h3>
<p><asp:Label ID="viewImageNoComments" runat="server" /></p>
<asp:Repeater ID="viewImageCommentsRepeater" runat="server">
<HeaderTemplate>
<div class="float_box marge wrapper comments">
</HeaderTemplate>
<ItemTemplate>
<div class="grid_25">
<span class="user"><%#Eval("username")%></span><br />
<span style="font-size:x-small; color:#666"><%#Eval("datetime") %></span>
</div>
<div class="grid_75">
<p align="justify"><%#Eval("com_text") %></p>
</div>
</ItemTemplate>
<FooterTemplate>
</div>
</FooterTemplate>
</asp:Repeater>
</div>
<!-- Post comment block -->
<div class="wrapper bloc content">
<h3><a id="post_comment" name="post_comment"><img src="img/comment_edit.png" alt="Comments" /></a> Post
a comment</h3>
<p class="description">Please be polite.</p>
<p>
<asp:Label ID="postCommentFeedback" runat="server" />
</p>
<table border="0">
<tr>
<td valign="top">
<asp:TextBox id="postCommentContent" runat="server" TextMode="MultiLine"
MaxLength="600" Columns="50" Rows="15" Width="400px" />
</td>
<td valign="top">
<span style="font-size:x-small">BBCode is enabled. Usage :<br />
<b>bold</b> : [b]bold[/b]<br />
<i>italic</i> : [i]italic[/i]<br />
<span class="style1">underline</span> : [u]underline[/u]<br />
Link : [url=http://...]Link name[/url]<br />
Quote : [quote=username]blah blah blah[/quote]</span>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="postCommentButton" runat="server" Text="Submit"
onclick="postCommentButton_Click" />
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
The postCommentButton_Click() function works just fine - clicking "Submit" will make the post. However, I need to completely reload the page in order to see new comments - the post the user just made will not show until then. I Databind the Repeater in Page_Load() after a (!isPostBack) check.
The postCommentButton_Click() function looks like this:
protected void postCommentButton_Click(object sender, EventArgs e)
{
// We check if user is authenticated
if (User.Identity.IsAuthenticated)
{
// Attempt to run query
if (Wb.Posts.DoPost(postCommentContent.Text, Request.QueryString["imageid"].ToString(), User.Identity.Name, Request.UserHostAddress))
{
postCommentFeedback.Text = "Your post was sucessful.";
postCommentContent.Text = "";
}
else
{
postCommentFeedback.Text = "There was a problem with your post.<br />";
}
}
// CAPTCHA handling if user is not authenticated
else
{
// CAPTCHA
}
}
In my case, we do see postCommentFeedback.Text refreshed, but, again, not the content of the repeater which should have one more post.
What is it I'm missing?
You should DataBind in the Page_Load within a !IsPostBack as you are. You should ALSO databind in your Click event.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.DataBind();
}
}
protected void MyButton_Click(object sender, EventArgs e)
{
//Code to do stuff here...
//Re DataBind
this.DataBind();
}
public override void DataBind()
{
//Databinding logic here
}
Instead of making your datasource a MySqlDataReader, have your reader populate a BindingList or something like that. Keep that in session and do your databind every non-postback and click. When your user posts, you can either add it to the list and wait for something to tell it to save that, but it makes more sense in the context of posting comments to save their post to your db and redo your datapull and stomp over your BindingList and re-Databind.
Also, personal peeve: I dislike <%#Eval....%>. Code in your page is usually a bad sign. Try using the Repeater.ItemDataBound Event
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound.aspx
It sounds to me like the quick fix is to bind on page load regardless of postback. Alternatively, you could rebind from within postCommentButton_Click.
protected void Timer1_Tick(object sender, EventArgs e)
{
Repeater1.DataBind();
/*This is all I did for it to work.*/
}
protected void Buttontextbox_Click(object sender, EventArgs e)
{
this.DataBind();
/*Leave sql connection to your database above "this.databind"*/
}
try putting the update panel between tags and if you have already done that then check if the closing of div tags is proper

Categories