ASP.Net GridView UpdatePanel Paging Gives Error On Second Click - asp.net

I'm trying to implement a GridView with paging inside a UpdatePanel. Everything works great when I do my first click. The paging kicks in and the next set of data is loaded quickly. However, when I then try to click a link for another page of data, I get the following error:
Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 12030
aspx code
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<contenttemplate>
<asp:GridView ID="GridView1" runat="server" CellPadding="2"
AllowPaging="true" AllowSorting="true" PageSize="20"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_PageSorting"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ActivityLogID" HeaderText="Activity Log ID" SortExpression="ActivityLogID" />
<asp:BoundField DataField="ActivityDate" HeaderText="Activity Date" SortExpression="ActivityDate" />
<asp:BoundField DataField="ntUserID" HeaderText="NTUserID" SortExpression="ntUserID" />
<asp:BoundField DataField="ActivityStatus" HeaderText="Activity Status" SortExpression="ActivityStatus" />
</Columns>
</asp:GridView>
</contenttemplate>
</asp:UpdatePanel>
code behind
private void bindGridView(string sortExp, string sortDir)
{
SqlCommand mySqlCommand = new SqlCommand(sSQL, mySQLconnection);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
mySqlAdapter.Fill(dtDataTable);
DataView myDataView = new DataView();
myDataView = dt.DefaultView;
if (sortExp != string.Empty)
{
myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
}
GridView1.DataSource = myDataView;
GridView1.DataBind();
if (mySQLconnection.State == ConnectionState.Open)
{
mySQLconnection.Close();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
protected void GridView1_PageSorting(object sender, GridViewSortEventArgs e)
{
bindGridView(e.SortExpression, sortOrder);
}
any clues on what is causing the error on the second click?

If anything on your page that is outside UpdatePanel, is changing after the first click, or try to change, on second click is comething diferent, but your calls did get again the fist one value because there are outside UpdatePanel and did not get the update value, just get the first one again -> So product an error on second click.
Probably you have out side the UpdatePanel some data thats need to be rendered correctly.
Keep inside UpdatePanel anything that you change and use with this control.
For example the sSQL, where do you store it ? Its change ? Maybe other value changes on click ?

Probably you have out side the UpdatePanel some data thats need to be rendered correctly. Keep inside UpdatePanel anything that you change and use with this control.

Related

Checkbox on GridView always returning False

I have a GridView with a Checkbox on the first column:
<asp:GridView ID="dgNumeradores" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="ItemID">
<Columns>
<asp:TemplateField HeaderText="Seleccionar">
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkChecked" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Item" DataField="Description">
</asp:BoundField>
<asp:BoundField HeaderText="Plantilla" DataField="Template">
</asp:BoundField>
</Columns>
</asp:GridView>
Now in the code behind I try to update the Checked column on the DataTable acting as datasource for the GridView (since, as you can see above, the Checkbox column is not bound to the datasource for reasons you probably know.):
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
For Each dr As GridViewRow In Me.dgNumeradores.Rows
Me.itemsNumTable.Select("ItemID = '" & dgNumeradores.DataKeys(dr.RowIndex).Value & "'")(0)("Checked") = DirectCast(dr.Cells(0).FindControl("chkChecked"), CheckBox).Checked
Next
'Some more unimportant-for-this-question code
Catch ex As Exception
tableInfo.ShowError(ex.Message)
End Try
End Sub
The thing is that the Checkbox.Checked always returns False.
How can I get the checked state of the Checkboxes in this scenario? Or what would be the best approach into updating the aforementioned column?
P.S. Note that click on the checkboxes doesn't post back. Nothing happens on the page until the user clicks Save (and that is the intended behavior).
Are you binding the GridView in Page Load? If that is the case use IsPostBack
IF Not IsPostBack Then
DataBind()
End IF
Should you not have the AutoPostback property set to true?
<asp:CheckBox runat="server" ID="chkChecked" AutoPostback="true" />
I have two columns in my GridView. The first column contains filenames,
the second column contains Checkboxes. Once the user has selected an arbitrary
number of Checkboxes then by clicking a button the selected files can be
downloaded.
My markup is as follows
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="Available Schemas"
DataField="SchemaFileName"
SortExpression="UserId">
</asp:BoundField>
<asp:TemplateField HeaderText="Select Schema">
<ItemTemplate>
<asp:CheckBox runat="server" ID="SelectedFiles" checked= '<%# Eval("checkValue") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My CodeBehind part is as follows
protected void Page_Load(object sender, EventArgs e)
{
GenerateDownloadLinks();
if (!IsPostBack)
{
GridView1.DataSource = listOfData;
GridView1.DataBind();
}
}
listOfData is populated in GenerateDownloadLinks() and then it is bind to GridView1.
Once the user selected files and clicks download then my code loops through
the rows of the GridView and when the CheckBox is checked it updates the initially
false value of the data entry to make sure which files should be made available for
download.
protected void GetFiles_Click(object sender, EventArgs e)
{
int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkRow = (row.Cells[1].FindControl("SelectedFiles") as CheckBox);
if (chkRow.Checked)
{
listOfData[i].CheckValue = true;
}
i++;
}
}
Gridview fills perfectly even when it is not binded in Page.IsPostBack block, but here checkbox will always return false.
Bind gridview in Page.IsPostBack, and it would run perfectly fine.
Use below code
IF Not IsPostBack Then
DataBind()
End IF
And then Checkbox.Checked will return true.

Invalid postback or callback argument - button in Telerik grid

Very famous error message (see below), judging by the number of Google results. But every one of them I've seen suggests to set EnableEventValidation to false. I have searched my entire codebase, and I cannot find the string "EnableEventValidation" anywhere. Moreover, this code used to work; something I have done has obviously broken the pages. But what?
The error happens when I click on a button inside a Telerik RadGrid, declared as:
<telerik:RadGrid ID="MyGrid" Width="100%" ItemStyle-BorderColor="Gainsboro"
ItemStyle-BorderStyle="Solid" ItemStyle-BorderWidth="1px" ActiveItemStyle-BackColor="Bisque"
SelectedItemStyle-BackColor="Black" AllowPaging="True" PageSize="15" runat="server"
AllowSorting="true" OnItemCommand="MyGrid_ItemCommand" AutoGenerateColumns="false"
OnNeedDataSource="MyGrid_NeedDataSource" GridLines="Horizontal" AllowMultiRowSelection="false"
Skin="Black">
<GroupingSettings CaseSensitive="false" />
<MasterTableView Width="100%" DataKeyNames="ID" AllowFilteringByColumn="false" Font-Names="Arial"
Font-Size="10px">
<Columns>
<telerik:GridButtonColumn ButtonType="PushButton" Text="Cancel" CommandName="Cancel"
ConfirmText="Are you sure you want to cancel this?">
</telerik:GridButtonColumn>
...
</Columns>
</MasterTableView>
<PagerStyle Mode="NextPrevAndNumeric" />
<FilterMenu EnableTheming="True">
<CollapseAnimation Duration="200" Type="OutQuint" />
</FilterMenu>
</telerik:RadGrid>
click on the "Cancel" button, and here's the famous error:
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> 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.
Here's the problem: in my Page_Load method I had:
protected void Page_Load(object sender, EventArgs e) {
MyGrid.Rebind();
}
The rebinding of the grid on postback was obviously screwing something up. I changed it to:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
MyGrid.Rebind();
}
}
and everything is working now.
I had the same problem but I had no Grid.Rebind() or Grid.Databind() in my NeedDataSource method or Page_Load method. This happened just after I drag a column to be grouped and then order the grouped column ASC/DESC
I simply added
EnableEventValidation="false"
in the <%# Page %> tag of my .aspx page. The ordering fails but at least I no longer get the error. As a note everything else works perfectly except the ordering of a grouped column
here is the code I use in the NeedDataSource method
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
String connstr = ConfigurationManager.ConnectionStrings["PrimeIntegartionsConnectionString"].ConnectionString;
SqlDataSource Ds = new SqlDataSource(connstr, BuildSql()); //buildsql simply returns a SQLSelect String "select * from example"
RadGrid1.DataSource = Ds;
}

ASP.NET GridView Data which i set on RowDatabound event loses after post back

I have an asp.net page where i have a gridview control which bind data from a DataTable.
In my 5 th column of the grid i am showing a Radio button list which has 2 Radio button items (Yes or No). For Some rows i will not show the RadioButton control, if the 4 th column cell value is empty. It works fine.But in my button click event (postback), the Grid is showing the Radio button list for those cells which was not shown initially. I have enabled ViewState for page and Control
This is my code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns=false
DataKeyNames="RequestDetailId" ondatabound="GridView1_DataBound" EnableViewState ="true" AllowPaging=false
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="RequestDetailId" HeaderText="Request Detail Id" />
<asp:BoundField DataField="Item" HeaderText="Item" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:BoundField DataField="NewOffer" HeaderText="New Offer" />
<asp:TemplateField HeaderText="Your Response" ItemStyle-CssClass="radioTD">
<ItemTemplate>
<asp:RadioButtonList ID="radioList" runat="server">
<asp:ListItem Text="Yes" Value="Accept"></asp:ListItem>
<asp:ListItem Text="No" Value="Reject"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
in code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadItemDetails();
}
}
private void LoadItemDetails()
{
DataTable objDt= GetGridDataSource();
if (objDt.Rows.Count > 0)
{
GridView1.DataSource = objDt;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(String.IsNullOrEmpty (e.Row.Cells[3].Text.Trim())||(e.Row.Cells [3].Text ==" "))
{
e.Row.Cells[4].Text = "";
}
}
My results are
Before Postback
After Postback
How do i maintain the content after postback ? Thanks
The problem is that you are setting the Text of the GridView table cell to an empty string rather than setting the visibility of the RadioButtonList control to false.
Clearing the Text property is removing the markup for the RadioButtonList on the first load, but on postback the RowDataBound event is not fired and the RadioButtonList control is recreated and displayed again.
To avoid this you could find the control and set its visibility to false, this will then be remembered across postbacks.
Try the following:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (String.IsNullOrEmpty(e.Row.Cells[3].Text.Trim()) || (e.Row.Cells[3].Text == " "))
{
RadioButtonList radioList = (RadioButtonList)e.Row.FindControl("radioList");
radioList.Visible = false;
}
}
Hope this helps.
you can do something like this ..
from the description of the problem. it sounds as if you are doing the databinding in the code behind. in such case asp.net does not preserve the datasource in the viewstate for you. try retrieving the data and storing it in the ViewState hashtable object with something like
ViewState["GridviewData"] = GridviewData
and retreiving it from there between postbacks

Problem with asp.net page results

hey guys,
recently while creating a webpage with a gridview, while binding the gridview with sql database, once when i run the site, it shows me the proper results, but when i make any changes and attempt to run the site again, it does not displays the latest changes, instead it displays the results from the previous cache, but when i clears the history, then when i refresh the page, it shows proper results.
Below is my code which i am using to bind my gridview.
SqlConnection con = new SqlConnection(#"[connection string goes here]");
public void FillGrid()
{
SqlDataAdapter adap = new SqlDataAdapter("select m.ModuleID, md.FriendlyName from Modules m inner join dbo.ModuleDefinitions md on m.ModuleDefID = md.ModuleDefID", con);
DataTable dt = new DataTable();
adap.Fill(dt);
FunGrid.DataSource = dt;
}
protected void Page_Load(object sender, EventArgs e)
{
FillGrid();
FunGrid.DataBind();
}
Below is the source of the gridview as i am using boundfields to bind gridview.
<form id="form1" runat="server">
<div>
<asp:GridView ID="FunGrid" runat="server" AllowPaging="True"
AutoGenerateColumns="False" PageSize="10">
<Columns>
<asp:BoundField DataField="ModuleId" HeaderText="Module ID" />
<asp:BoundField DataField="FriendlyName" HeaderText="Module Name" />
</Columns>
</asp:GridView>
</div>
</form>
This is the first time i have got some issues like that, Please if anyone guys have came accross such issues please revert back with the resolutions...
Thanks and Regards
Abbas Electricwala
You can disable caching for the page:
<%# OutputCache Location="None" VaryByParam="None" %>
or add this to your page response:
Response.Cache.SetCacheability(HttpCacheability.NoCache);

GridView Checkbox Columns vs. Events

I have created a gridview with a column of checkboxes. I want the user to select the checkboxes, click the register button (outside the gridview), and have a title from the selected row displayed. From what I've read I should put the checkbox check in the button click event. I have done so, but apparently the only time it enters that event is at page load and right before the page loads, all the selected checkboxes are wiped. Therefore, my check for a selected checkbox never comes out true. Is there an event that would a better time to run this check, or perhaps a way to hold these values through the page load? The following isn't all my code, just the affected portions.
protected void regButton_Click(Object sender, EventArgs e)
{
StringBuilder regClasses = new StringBuilder();
for (int i = 0; i < SQLQueryClassListings.Rows.Count; i++)
{
//Response.Write(SQLQueryClassListings.Rows[i].Cells[0].Text + " checkbox check ");
GridViewRow checkRow = SQLQueryClassListings.Rows[i];
bool reg = ((CheckBox)(checkRow.FindControl("RowCheckBox"))).Checked;
if (reg)
{
regClasses.Append(SQLQueryClassListings.Rows[i].Cells[0].Text + " ");
}
}
Response.Write(regClasses);
}
<asp:GridView ID="SQLQueryClassListings" AutoGenerateColumns="false" runat="server"
BorderWidth="1px" BackColor="White" CellPadding="5" BorderColor="Black" RowStyle-BorderColor = "Black"
HeaderStyle-BackColor="#0D69F2" HeaderStyle-ForeColor="White" AlternatingRowStyle-BackColor="#E8E8E8" HeaderStyle-BorderColor="Black" GridLines="Both">
<Columns>
<asp:BoundField HeaderText="Classes" DataField="LeafName" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="250"
ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:BoundField HeaderText="Teacher" DataField="TeacherName" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="200"
ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:BoundField HeaderText="Available" DataField="SemesterEnds" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign ="Center" ItemStyle-Width="150" ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:HyperLinkField HeaderText="Course Description & Career Tracks" DataNavigateUrlFields="ApplicableTracks"
Text="See Description" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign ="Center" ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:TemplateField HeaderText="Register" HeaderStyle-BorderColor="Black" ItemStyle-BorderColor = "#ADADAD" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox runat="server" ID="RowCheckBox"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p>
<asp:Button ID="Button1" runat="server" Text="Register" OnClientClick="return confirm('You have sucessfully registered!')"
OnClick="regButton_Click" />
You need to get on the ItemDataBound event of the GridView control, find the CheckBox by ID, and do whatever you need.
It's hard to know for sure without seeing more of your code, but it sounds like your page is re-binding the GridView on postbacks (such as your regButton_Click event). So it rebuilds the GridView every time the page loads - even after your user clicks the register button.
If that is the case, you can fix this by changing the code you use to bind your GridView like this:
if (!this.IsPostback) {
SQLQueryClassListings.DataBind();
}
(This presumes that you have ViewState enabled for the page (or at least the GridView). There are other mechanisms you can use to communicate the client's state (such as checkbox selections) to the server, but ViewState (for all its faults) is the default tool for doign so in ASP.NET.)
A consequence is that the data shown in the GridView won't be completely up-to-date, but if you can tolerate that, this is a simple way to accomplish what you want.
You must read the checkboxes from the GridView.
So this code will bring back the IDs of the rows checked. It will give you the idea and then you can change it for what you need.
protected string getCheckedIds(GridView gv)
{
StringBuilder sb = new StringBuilder();
foreach (GridViewRow gvr in gv.Rows)
{
if (!gvrIsChecked(gvr)) // see below for this method
continue;
if (sb.Length > 0)
sb.Append(",");
sb.Append(gv.DataKeys[gvr.DataItemIndex].Value);
}
return sb.ToString();
}
protected bool gvrIsChecked(GridViewRow gvr)
{
// The location of your checkbox may be different.
object cb = gvr.Cells[0].Controls[gvr.Cells[0].Controls.Count - 2];
if (cb.GetType() != typeof(CheckBox))
return false;
if (!((CheckBox)cb).Checked)
return false;
return true;
}

Resources