Breakpoint not hitting on ItemDataBound function - c#

I have a grid control called RadGrid1 and with a breakpoint in RadGrid1_ItemDataBound, but when I run my aspx application, the breakpoint is not being triggered.
my code is:
<telerik:RadGrid ID="RadGrid1" runat="server" Width="980px" CssClass="GridDisplay"
AllowAutomaticDeletes="false" AllowAutomaticInserts="false" AllowAutomaticUpdates="true" AllowPaging="true"
AutoGenerateColumns="False" AutoGenerateDeleteColumn="false" AutoGenerateEditColumn="false" ItemStyle-Height="20px"
ClientSettings-ActiveRowIndex="true" EnableViewState = "false" OnDeleteCommand = "RadGrid1_OnDelete"
OnItemCreated = "RadGrid1_ItemCreated" OnItemDatabound = "RadGrid1_ItemDatabound" OnNeedDataSource = "RadGrid1_NeedDataSource">
<telerik:GridTemplateColumn DataField="Confirmed" HeaderText="Confirmed" UniqueName="Confirmed" Visible="true">
<ItemTemplate>
<asp:CheckBox ID="chkVerified" runat="server" AutoPostBack="true"
Checked='<%# bool.Parse(Eval("Verified").ToString()) %>'
Enabled='<%# !!Convert.ToBoolean(Convert.ToInt32(Eval("Verified").ToString())) %>'
ToolTip='<%# Eval("NoConfirmDesc").ToString() %>'
/>
</ItemTemplate>
</telerik:GridTemplateColumn>
aspx.cs
private void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{ }
}

In aspx, the handler for Databound event is called RadGrid1_ItemDatabound
OnItemDatabound = "RadGrid1_ItemDatabound"
but in code behind, your method is spelled with capital B in databound
void RadGrid1_ItemDataBound
Make sure you place the breakpoint inside the right method.

Could you make sure AutoEventWireup="true" for the page?
<%# Page ... AutoEventWireup="true" %>
In addition, make sure that there are not spaces between them OnItemDatabound="RadGrid1_ItemDatabound"
One thing I notice in your code is you want to use OnNeedDataSource to bind Data if you use RadGrid.
OnNeedDataSource="RadGrid1_NeedDataSource"

maybe you forgot to register or are not correctly registering the OnItemDataBound Event
Or maybe you are not databinding the control?
RadGrid1.DataSource= mydatasource;
RadGrid1.DataBind();
As last possibility maybe iis express and visualstudio debugger are not working correclty
I suggest to kill iisexpress process and then rebuild the solution then try again

Related

Event in Update panel is not fired after rebinding control after Postback

I have a Gridview together with some LinkButton inside of an Update Panel. The click events are fired correctly, the way I expect them to work. BUT: After adding an additional Header Row to the grid in code behind, I need to rebind the Grid after each postback. Since then the click causes a postback, but the method is not executed.
<asp:UpdatePanel runat="server" ID="UpdatePanel2" UpdateMode="Always">
<ContentTemplate>
<asp:GridView ID="GridViewFollowUpMove" runat="server" AutoGenerateColumns ="false" OnRowDataBound="FollowUp_RowDataBound" OnDataBound="FollowUpMove_OnDataBound">
<Columns>
<asp:TemplateField HeaderText="Due date" ItemStyle-HorizontalAlign="left">
<ItemTemplate>
<asp:LinkButton ID="LB_DueDate" runat="server" OnClick="ActivateDueDate" CssClass="NoDeco" CommandArgument='<%# Bind("ISSUEID") %>'>
<asp:Label ID="LabelDueDate" runat="server" Text='<%# Bind("DueDate","{0:dd.MM.yyyy}") %>' Width="60px" Class="line"/></asp:LinkButton>
<asp:TextBox ID="TXTBX_DueDate" runat="server" Text='<%# Bind("DueDate") %>' Font-Size="11px" visible="false" OnTextChanged="TextChanged_DueDate" AutoPostBack="true"/>
</ItemTemplate>
</asp:TemplateField>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FillFollowUp();
}
FillFollowUp();
}
I solved this problem by moving the commands that create and customize the additional Header row to the OnRowCreated Event. As I read somewhere: When a postback occurs, the Gridview must be recreated on the server, and in this process ItemCreated is fired for each item, but ItemDataBound is not (since the control properties are pulled from ViewState).
So building these headers in DataBound is the wrong choice!

"Failed to load view state" Error When dynamically loading user control

I am having a User control [ascx] which is a radgrid. It also has a Edit column template which allow user to Insert/ change/update the values.
I am loading this user control on click of a button [Say EDIT] in aspx page.
When I click on EDIT button of aspx page the user control loads perfectly, but when I click on the Add New Record of user control I get this error message.
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save
viewstate during the previous request. For example, when adding
controls dynamically, the controls added during a post-back must match
the type and position of the controls added during the initial
request.
//code of user control -ascx
<telerik:RadGrid AllowAutomaticDeletes="True"
AllowAutomaticInserts="False" AllowAutomaticUpdates="False"
Height="410px" ID="rgrd1" runat="server" AutoGenerateColumns="False"
OnUpdateCommand="rgrd1_UpdateCommand"
OnInsertCommand="rgrd1_InsertCommand" OnNeedDataSource="rgrd1_NeedDataSource" GridLines="None">
<MasterTableView CommandItemDisplay="top" CommandItemStyle-Wrap="False" CommandItemStyle-HorizontalAlign="Left"
DataKeyNames="Type">
<Columns>
<telerik:GridEditCommandColumn UniqueName="EditColumn" HeaderStyle-HorizontalAlign="left"
HeaderText="Edit" ButtonType="ImageButton">
</telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn DataField="Type" HeaderStyle-HorizontalAlign="left"
HeaderText="Type" UniqueName="Type">
<ItemTemplate>
<asp:Label ID="TypeLabel" runat="server" Text='<%# Eval("Type") %>'></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
<EditFormSettings EditFormType="Template">
<EditColumn FilterControlAltText="Filter EditCommandColumn1 column" UniqueName="EditCommandColumn1">
</EditColumn>
<FormTemplate>
<table>
<td>
<telerik:RadTextBox ID="txtType" Width="50" runat="server" Text='<%# Eval("Type") %>'>
</telerik:RadTextBox>
</td>
</tr>
</table>
</FormTemplate>
</EditFormSettings>
</MasterTableView>
<HeaderStyle HorizontalAlign="Center" />
</telerik:RadGrid>
.....................................
Code of my aspx page - in which i am loading the above usercontrol in Radwindow
On click of EDIT button - below code i have written-
RadWindow window = new RadWindow();
window.Height = Unit.Pixel(500);
window.Width = Unit.Pixel(500);
window.VisibleOnPageLoad = true;
UserControl uc = (UserControl)Page.LoadControl("../../Controls/TypeUserControl.ascx");
uc.EnableViewState = false;
window.ContentContainer.Controls.Add(uc);
pnl.Controls.Add(window);
When I click on Add New Record in usercontrol it throws the exception "Failed to load view state:"
I have aspx page on which this user control is loaded is being inherited by my BasePage.
Exception is coming in OnPreRender of base page
protected override void OnPreRender(EventArgs e)
{
try
{
base.OnPreRender(e);
}
}
User control - code behing
public partial class TypeUserControl : System.Web.UI.UserControl
{
protected void rgrd1Types_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
try
{
//dbase call
}
catch (Exception ex)
{
SetValidationMessage(ex.Message.ToString());
}
}
protected void rgrd1_InsertCommand(object source, GridCommandEventArgs e)
{
try
{
//dbase call
}
catch (Exception ex)
{
SetValidationMessage(ex.Message.ToString());
}
}
I don't know if this is the issue, but your HTML is not correct in your Form Template
<table>
<td>
<telerik:RadTextBox ID="txtType" Width="50" runat="server" Text='<%# Eval("Type") %>'>
</telerik:RadTextBox>
</td>
</tr>
</table>
you are missing the opening <tr> tag. this could have something to do with the issue.
you should double check all your code to make sure that it is correct.
--
I am also guessing that you should remove this line of code from the Edit button's OnClick() event
uc.EnableViewState = false;
You have to recreate the control on postback as you add it dynamically.
Recreate or Add the control in the Init_page Eventhandler, there you can check the type of event or control, that caused the postback, to know that you should recreate this control.
Can you post the code-behind file.
EDIT:
It's a long time ago, when I did this. But here is a working example.
I think there is a better way.
Check the keys collection, which button caused the postback, if it is a certain button in your ascx control then readd your control to the page or whereever you put it, but it must be the same place on postback, otherwise you will get an error, I think.
protected override void OnInit(EventArgs e) { base.OnInit(e);
if (this.Page.IsPostBack) {
var x = base.DeterminePostBackMode();
if (x.Keys.Get(3).Contains("btnInControl"))
{
Control ctrl = Page.LoadControl("WebUserControl1.ascx");
this.Page.Form.Controls.Add(ctrl);
}
}
}
It has been a year since you posted this issue but just in case someone still facing this: here is the main root of this type of error. I have been struggling big time with it.
The easiest way to fix your bug is to set to the control you add dynamically :
EnableViewState = false
If you need the Viewstate, the other options you have are to add the control you add dynamically onInit, or recreate it on every Postback.
Hope it helps.
See Funkylife's comment for more information.

Button inside a repeater is not functioning

I have two buttons inside of the repeater and I'm trying to access them from code behind, but they are not working. I receive the following error:
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
I don't understand what does the error mean nor where is coming from. Here is my code:
<asp:Repeater ID="Repeater1" runat="server"
onitemdatabound="Repeater1_ItemDataBound1"
onitemcommand="Repeater1_ItemCommand" >
<ItemTemplate>
<table>
<tr>
<td><asp:Image ID="Image1" runat="server" /></td>
<td><asp:Label ID="empnamelbl" runat="server" Text='<%# Eval("fullname") %>'></asp:Label></td>
<td><asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList></td>
<td> <asp:Button ID="Button1" runat="server" Text="Present" CommandName="test1" CommandArgument='<%# Eval("ID") %>' /> </td>
<td><asp:Button ID="Button2" runat="server" Text="Absent" CommandName="test2" CommandArgument='<%# Eval("ID") %>' /> </td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "test1")
{
Response.Write("hi");
}
}
I was able to solve it by using, UseSubmitBehavior="false", property in the buttons.
Here is it:
<asp:Button ID="Button2" UseSubmitBehavior="false" runat="server" Text="Absent" CommandName="test2" CommandArgument='<%# Eval("ID") %>' />
Try setting EnableViewState="false" for the repeater. Definitely there will be some drawbacks but this has worked for me.
Else below are some more approaches you can try on:
If you are setting your Repeater's DataSource in Page_Load event.
Try wrapping your Page_Load code inside if(!IsPostBack) .
protected void Page_Load( object sender , eventArgs e)
{
if(!IsPostBack)
{
// bind repeater , dropdownlist items ... here
}
}
Also from your error message it seems that enableEventValidation=“true” setting is present either in your Page as:
<%# Page EnableEventValidation="true" ... %>
OR in your web.config :
<system.web>
<pages enableEventValidation="true"/>
</system.web>
Some suggestions:
Disable eventvalidation. Easy to do but less secure .THIS IS NOT RECOMMENDED. Also read here an extremely good article on this issue: http://odetocode.com/blogs/scott/archive/2006/03/22/asp-net-event-validation-and-invalid-callback-or-postback-argument-again.aspx
If any client side method is used to set changes in Controls, It's better to use the
postback and add or remove the items server-side. Example: if a list control includes options numbered 1, 2, or 3 when the page is rendered, and if a postback request is received specifying option number 4, ASP.NET raises an exception.
This MSDN reference. is good too.
I hope this helps.
due to presence of Image that run at server .. try to use img tag instead

PostBackTrigger on multiple LinkButtons in an update panel

I have a search form in an updatePanel which retrieves a list of users in a grid in the same UpdatePanel. The name of each user is a commandLink. I want to make the commandLinks as PostBackTriggers.
But when I do it I get an error at the pageLoad time that the controlId does not exist and its true because the grid of users does not render at the load time but through an ajax call.
Any ideas on how can I make the multiple command buttons in a grid retrieved through ajax call as post back triggers?
When adding the items to the grid, within the ItemDataBound event handler, you should register the postback for each specific control (the static identifiers in your HTML declarations are essentially placeholders - not all things repeated in the grid can actually have the same ID). You do this using the ScriptManager.RegisterAsyncPostBackControl method:
The RegisterAsyncPostBackControl method enables you to register Web
server controls as triggers so that they perform an asynchronous
postback instead of a synchronous postback. When the
ChildrenAsTriggers property of an UpdatePanel control is set to true
(which is the default), postback controls inside the UpdatePanel
control are automatically registered as asynchronous postback
controls.
As stated above, using ChildrenAsTriggers is a possibility, too, but this is commonly set to false for more stringent management.
I have found the solution. Here is the code on asp
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" Text="Search" />
<asp:GridView ID="gvSearchResult" runat="server" OnRowCommand="gvSearchResult_RowCommand"
OnRowDataBound="gvSearchResult_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnDetail" runat="server" CommandArgument='<%# Bind("CNIC") %>' CommandName="Detail">
<asp:Label ID="lblName" Text='<%# Bind("Employee_Name") %>' runat="server</asp:Label>
</asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle"Height="25px"Width="30%" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Ihad to place OnRowDataBound="gvSearchResult_RowDataBound" on gridView and that function looks like below. So I had to register the iterative control in Scriptmanager as PostBackControl in RowDataBound event of GridView.
protected void gvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
LinkButton lnkbtnDetail = (LinkButton)e.Row.FindControl("lnkbtnDetail");
ScriptManager.GetCurrent(this).RegisterPostBackControl(lnkbtnDetail);
}
}
catch (Exception ex)
{
}
}

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
}

Categories

Resources