CommandName not visible in source code - c#

I have this code
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Command1">
<img src="../images/image1.png" alt="" />
</asp:LinkButton>
</ItemTemplate>
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
and this code
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Command1")
{
// Never drops here
}
}
The event is being triggered.
But when I debug, LinkButton1's CommandName is not visible in source code.
So, the if statement doesn't work.
Any ideas ?
Edit :
I realised that I have an other error my page that belongs this situation.
Then I used GridView rather than DataList and used the GridView's RowCommand Event and fixed this.

The reason is because your attempting to obtain the CommandName from the DataList not the LinkButton. Your code would work if you did the following:
protected void btnSample_Click(object sender, EventArgs e)
{
// Instantiate:
var command = ((LinkButton)sender).CommandName;
// Do additional logic.
}
I believe your intent is to actually do something on the Click Event. If that isn't your case, you would need to FindControl on an event within your DataList, then instantiate the LinkButton to obtain the CommandName. Hopefully this points you in the proper direction.
I would do a sample within the DataList, but without exact implementation and additional information I wouldn't be able to. It would be similar to the above, just allocating the Control within the current control.

Related

Data not bound for ListView on postbacks

I am writing some message panel as a user control. The code looks like this (shortened for clarity)
protected void Page_PreRender(object sender, EventArgs e)
{
BindMessages(MessageType.Error, ErrListView);
}
private void BindMessages(MessageType type, ListView target)
{
List<string> messages = Session.PopMessages(type);
target.DataSource = messages;
target.DataBind();
}
ascx:
<asp:ListView runat="server" ID="ErrListView">
<ItemTemplate><li><%# Container.DataItem %></li></ItemTemplate>
</asp:ListView>
The code gets executed on each request (initial page load and postback) as it should, and the messages come out of the SessionState correctly. However, if the request is a postback, the messages are not actually updated (as if the DataBind() would not happen).
Anyone got a clue whats going on?
The reason I failed here was that my content did not contain an UpdatePanel. Changing my ascx file to include said control resolved my issues.
<asp:UpdatePanel runat="server" ID="StatusUpdatePanel">
<ContentTemplate>
<ul Class="Errors">
<asp:ListView runat="server" ID="ErrListView">
<ItemTemplate><li><%# Container.DataItem %></li></ItemTemplate>
</asp:ListView>
</ul>
</ContentTemplate>
</asp:UpdatePanel>

Calling a functon in code behind by using an imagebutton in a gridview

I have an ImageButton within a GridView in .aspx on clicking this ImageButton i have to call a function.
This is how i tried and the function was not being called.
Code inside.aspx page:
<GridView ......>
<asp:HyperLink ID="HyperLink2" runat="server"
NavigateUrl='<%# DataBinder.Eval(Container.DataItem,"VehID","mngVeh.aspx?delid={0}") %>'>
<asp:ImageButton runat="server" ID="DeleteUrlImageButton"
width='24' height='24'
ImageUrl="~/images/delete.jpeg"
OnClick="DeleteUrlImageButton_Click"
OnClientClick="return confirm('Are you sure you want to delete?');" />
<!--<img src="images/delete.jpeg" alt='edit' border="0" width='24' height='24'/> -->
</asp:HyperLink>
</GridView>
code in .aspx.cs page:
public void DeleteUrlImageButton_Click(object sender, EventArgs e)
{
//code to perform the necessary action.
}
Because you are wrapping your ImageButton inside of a Hyperlink, the browser is probably going to the hyperlink's URL instead of posting back to hit the OnClick function. You should have the DeleteUrlImageButton_Click function call Server.Transfer or Response.Redirect to the appropriate URL and get rid of the Hyperlink.
Sure it won't be fired because it is nested in a Hyperlink. So the imagebutton serves as the text for the hperlink and hyperlink does not cause postback. ImageButton can cause the desired action only if it stands out of the Hyperlink. Try this:
<asp:GridView ....
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton runat="server" ID="DeleteUrlImageButton"
width='24' height='24'
ImageUrl="~/images/delete.jpeg"
OnClick="DeleteUrlImageButton_Click"
OnClientClick="return confirm('Are you sure you want to delete?');"
PostBackUrl='<%# DataBinder.Eval(Container.DataItem,"VehID","mngVeh.aspx?delid={0}")
%>'/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
ImageButton can do the job no need for Hyperlink just use the postbackurl and it will redirect you to the page. You can omit the HyperLink.
Button controls (like LinkButton,ImageButton and Button) are designed to cause postback by default.
Edit: Make sure event name and arguments are correct. This is the event I used to test it. y the way don't forget to place the ImageButton in a TemplateField, refer the code above
protected void DeleteUrlImageButton_Click(object sender, ImageClickEventArgs e)
{
TextBox5.Text = "Fired ";
//Response.Redirect( ((ImageButton)sender).PostBackUrl);//uncomment this if the button does not automatically redirects. This line should be the last one
}

How to create and use custom control with UpdatePanel added to the page programmatically

I have simple web user control (the code I found somewhere in the web):
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs"
Inherits="ARP.DynamicsCRM2011.MagicWebForm.WebUserControl1" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox1_CheckedChanged"
Text="Checkbox" />
<asp:Button ID="Button1" runat="server" Text="Button" Visible="False" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
Button1.Visible = CheckBox1.Checked;
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
}
Now I want to add this control to my page (programmatically in OnLoadComplete event):
<%# Reference Control="~/WebUserControl1.ascx" %>
WebUserControl1 myControl = (WebUserControl1)Page.LoadControl("~/WebUserControl1.ascx");
myControl.ID = "myControl_" + some_name;
parentControl.Controls.Add(myControl);
Of course I have SriptManager on the page and my control is added properly. I know that programmatically added controls must be recreated every time the page is loaded. Unfortunately this causes creating new control, so checking checkbox doesn't work - after checking it the OnLoadComplete (of the page) is fired again and new control is created. If I omit that then nothing is displayed. So the question is - how to do this?
Dynamic control should be re-added to the control tree OnPreInit, see documentation:
PreInit - Create or re-create dynamic controls.
ASP.NET Page Life Cycle Overview
You can add that control on button click and save count of added controls in some storage like Session. The in Page_Init you need to check that count value and recreate each control you have add before.

ASP.NET ImageButton Onclick Event not handled

I have an ImageButton in a GridView.
<asp:GridView ID="ItemGridView" runat="server" DataKeyNames="Id"
OnRowDataBound="ItemGridView_RowDataBound" AllowPaging="True"
AllowSorting="True" EnableSortingAndPagingCallbacks="True"
AutoGenerateEditButton="False" AutoGenerateDeleteButton="false"
DataSourceID="ItemDataSource" EnableViewState="true" >
....
<asp:TemplateField ShowHeader="False" ItemStyle-Width="40px">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" SkinID="btnDelete"
runat="server" CausesValidation="false"
OnClick="btnDeleteAccountItem_Click"
OnClientClick="javascript:return confirm('Are you sure?');" />
</ItemTemplate>
</asp:TemplateField>
and a corresponding handler for the delete button event
protected void btnDeleteAccountItem_Click(object sender, EventArgs e) {
ImageButton btnDel = sender as ImageButton;
GridViewRow row = (GridViewRow)btnDel.NamingContainer;
....
}
I am using this very same construct in many places and it works fine. I have one gridview now, though, where it does not, and I am hoping to get some ideas for how to track down the problem.
When I click the button, the client-side event fires and the alert box is displayed, then the post-back fires and I can hit a break point in the Page_Load method. So the client-side wiring of the button events seems to work. However, the event is not handled and the method btnDeleteAccountItem_Click does not get called.
This is a complex page and I cannot post all the code. What can I do to narrow down potential causes?
Your event is defined incorrectly ImageButton.Click:
protected void btnDeleteAccountItem_Click(object sender, ImageClickEventArgs e) {
ImageButton btnDel = sender as ImageButton;
GridViewRow row = (GridViewRow)btnDel.NamingContainer;
....
}
I'm not sure if this will solve it, but once I placed a asp:Button control in my markup and generated the 'onClick' signature for it too.
I then changed my mind and decided to make it an Image button... ... I simply rewrote the tag myself.
After making those changes, I realised that the onClick signature wasn't working anymore... after some research I found an answer... I was using 'EventArgs' instead of 'ImageClickEventArgs'...
(object sender, ImageClickEventArgs e)
Once I changed the event arg object, it started working as normal.
rather than creating a button click event, you could use the datagrid row command event
You can then use e.commandName and e.commandArgument to find out which button was pressed and what its argument is:
Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand
If e.CommandName = "Whatever" Then
// do something
End If
Hope it helps
make sure the CausesValidation is set to True.
You can try (you are creating wrong click event of ImageButton) :
<asp:TemplateField ShowHeader="False" ItemStyle-Width="40px">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" SkinID="btnDelete" runat="server"
CausesValidation="false" OnClick="btnDeleteAccountItem_Click"
OnClientClick="javascript:return confirm('Are you sure?');" />
</ItemTemplate>
</asp:TemplateField>
and for image button there are change in click event like as follow :
protected void btnDelete_Click(object sender, ImageClickEventArgs e)
{
ImageButton btnDel = sender as ImageButton;
GridViewRow row = (GridViewRow)btnDel.NamingContainer;
}

ASP.NET user control: Page_Load fires before property is set

This is driving me crazy.
I have a very simple user control:
public int? ImageId {set; get;}
protected void Page_Load(object sender, EventArgs e)
{
... do something with ImageId...
}
And then I put this control on the page with ListView within UpdatePanel:
<asp:ListView ID="ListViewImages" runat="server" DataSourceID="src">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<My:MyControl ImageId='<%# Eval("Id") %>' ID="cipPreview" runat="server" />
</ItemTemplate>
</asp:ListView>
The problem is Page_Load fires BEFORE ASP.NET sets ImageId. With debugger's help I found out that for some reason ImageId in MyControl IS SET, but it happens only after Page_Load has finished processing. What's wrong?
It's probably because data binding on the ListView happens AFTER Page_Load fires, so therefore your property isn't set at that point. You could move your code to PreRender event since it is called after data binding is completed.
More info according to MSDN:
PreRender -- Before this event occurs:
The Page object calls EnsureChildControls for each control and for the page.
Each data bound control whose DataSourceID property is set calls its DataBind method.

Categories

Resources