Finding controls within Devexpress ASPxGridView - c#

I have a code that contains an ASPxGridView and a ASPxCheckBox and Label within in like:
<dx:ASPxGridView ID="gvTableSearchHomes" runat="server" DataSourceID="XmlHomes" Width="341px"
CssClass="tableViewSearchGrid" ClientInstanceName="gvTableSearchHomes"
AutoGenerateColumns="False" EnableRowsCache="false" KeyFieldName="ID">
<%--<Columns>--%>
<%-- DXCOMMENT: Within ASPxGridView, add a column whose values will participate in filtering --%>
<%--<dx:GridViewDataTextColumn FieldName="Address">
<PropertiesTextEdit NullText="Search your home"></PropertiesTextEdit>
<Settings AllowAutoFilterTextInputTimer="True" AutoFilterCondition="Contains" />
</dx:GridViewDataTextColumn>
</Columns>--%>
<Templates>
<%--DXCOMMENT: Configure the grid's DataRow template in accordance with data source fields --%>
<DataRow>
<div class="gvItem">
<dx:ASPxCheckBox ID="ChkBookList" runat="server"></dx:ASPxCheckBox>
<dx:ASPxLabel ID="Address" runat="server" CssClass="address" Text='<%# Utils.ExtractFirstRow(Eval("Address")) %>' />
<%--<p><dx:ASPxLabel ID="Address2" runat="server" CssClass="address2" Text='<%# Utils.ExtractSecondRow(Eval("Address")) %>' /></p>
<p><dx:ASPxLabel ID="Price" runat="server" CssClass="price" Text='<%# Utils.GetPrice(Eval("Price")) %>' /></p>--%>
</div>
</DataRow>
</Templates>
<SettingsPager Visible="false" PageSize="1000" />
<Settings ShowVerticalScrollBar="True" ShowFilterRow="true" ShowColumnHeaders="false"/>
<SettingsBehavior AutoExpandAllGroups="true" AllowSelectSingleRowOnly="true" AllowSelectByRowClick="true"/>
<ClientSideEvents
Init="function(){ hr.TableViewLandscape_Adjust(); }"
EndCallback="function(){ hr.TableViewLandscape_Adjust(); }"
SelectionChanged="OnGvTableSearchHomesSelectedChanged" />
<Styles>
<SelectedRow ForeColor="White"></SelectedRow>
</Styles>
I am not able to access these cotnrols through C# code. Can anybody help me. Please

Check the documentation methods to find controls in different gridview templates.
e.g. ASPxGridView.FindRowTemplateControl Method
Source: http://developmentsolutionsjunction.blogspot.in/2011/11/find-controls-in-dataitemtemplate-of.html
//markup
<dx:ASPxGridView ID="grvTest" AutoGenerateColumns="False" runat="server" DataSourceID="SqlDataSource1"
OnHtmlRowPrepared="grvTest_HtmlRowPrepared" OnHtmlRowCreated="grvTest_HtmlRowCreated">
<Columns>
<dx:GridViewDataTextColumn Caption="RowID" Name="colRowID" VisibleIndex="0" Width="20px">
<DataItemTemplate>
<dx:ASPxLabel ID="lblRowID" runat="server" Text='Label'>
</dx:ASPxLabel>
</DataItemTemplate>
</dx:GridViewDataTextColumn>
//accessing template control in code-behind
protected void grvTest_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
{
if (e.RowType != GridViewRowType.Data) return;
ASPxLabel label = grvTest.FindRowCellTemplateControl(e.VisibleIndex, null,
"lblRowID") as ASPxLabel;
label.Text = (e.VisibleIndex + 1).ToString();
}
example code:
ASPxGridView grid = (ASPxGridView)sender;
ASPxPageControl myPages = grid.FindEditFormTemplateControl("CityEditTabs")
as ASPxPageControl;
References:
How can I write events for the controls used in my Grid templates
Some GridView code snippets to understand gridview concepts
Identify the VisibleIndex or RowHandle to get the control in particular template that you have created in your markup.
Hope above example will help you to solve your problem.

thanks I solved mi problem. I put this
Protected Sub GvEncuesta_HtmlRowCreated(sender As Object, e As ASPxGridViewTableRowEventArgs)
If (e.RowType <> GridViewRowType.Data) Then Return
Try
Dim cmbRespuesas As ASPxComboBox = GvEncuesta.FindRowCellTemplateControl(e.VisibleIndex, Nothing, "ASPxCmbRespuestas")
cmbRespuesas.IncrementalFilteringMode = IncrementalFilteringMode.Contains
cmbRespuesas.Visible = True
cmbRespuesas.DataSource = wcfCap.RetrieveRespuestaEncuestaxEstado(1)
cmbRespuesas.ValueField = "Cod_Respuesta"
cmbRespuesas.TextField = "Nombre_Respuesta"
cmbRespuesas.DataBindItems()
Catch ex As Exception
End Try
End Sub

Related

How does Control.Enabled work?

I have spent several days looking at various resources and am getting more confused. I have several controls in a .aspx file: an edit button, a year dropdownlist, and four gridviews with textboxes and dropdownlists in them. The textboxes and dropdownlists in the gridviews start disabled. When the user clicks the edit button, they should enable. This works the first time, but they won't disable again. Here's the relevant code:
private void toggleEditMode()
{
editBtn.CssClass = editBtn.Attributes["mode"].ToString() == "edit" ? "btn btn-success" : "btn btn-primary";
editBtn.Text = editBtn.Attributes["mode"].ToString() == "edit" ? "<span class='glyphicon glyphicon-floppy-disk'></span> Save" : "<span class='glyphicon glyphicon-edit'></span> Edit";
editBtn.Attributes["mode"] = editBtn.Attributes["mode"].ToString() == "edit" ? "save" : "edit";
selectYear.Enabled = !selectYear.Enabled;
foreach (GridView gv in panels)
{
foreach (GridViewRow gvr in gv.Rows)
{
TextBox name = (TextBox)gvr.FindControl("nameTB");
DropDownList rating = (DropDownList)gvr.FindControl("ratingDDL");
name.Enabled = !name.Enabled;
rating.Enabled = !rating.
}
}
}
The edit button turns into the save button properly, and the year dropdownlist toggles correctly, but the textboxes and dropdownlists in the gridview won't disable. During debugging, I have discovered that the Enabled property of each textbox and DDL is false at the beginning of this method.
The textboxes and DDL's all start disabled, enable on the button click, and then won't disable, even though the button and year DDL toggle correctly.
My question is: how exactly does the Enabled property work? Any help is greatly appreciated.
EDIT: here is the markup:
<asp:LinkButton ID="editBtn" runat="server" ClientIDMode="Static" OnClick="ToggleEditMode" CssClass="btn btn-primary" mode="edit">
<span class="glyphicon glyphicon-edit"></span> Edit
</asp:LinkButton>
<div class="form-inline" role="form">
<fieldset>
<div class="form-group">
<label for="selectYear">Year: </label>
<asp:DropDownList ID="selectYear" runat="server" CssClass="form-control" AutoPostBack="true" ClientIDMode="Static"></asp:DropDownList>
</div>
</fieldset>
</div>
And here is the gridview:
<asp:GridView ID="jrSchools1a2aAdmin" runat="server" AutoGenerateColumns="false" GridLines="None" ClientIDMode="Static" OnRowCreated="BindRatings" CssClass="table table-striped table-bordered">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="nameTB" runat="server" Text='<%# Eval("name") %>' ClientIDMode="Static" schoolID='<%# Eval("schoolID") %>' Enabled="false" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:DropDownList ID="ratingDDL" runat="server" SelectedValue='<%# Eval("rating") %>' ClientIDMode="Static" Enabled="false" CssClass="form-control"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="students" HeaderText="Students" />
<asp:BoundField DataField="7_1" HeaderText="7-I" />
<asp:BoundField DataField="7_2" HeaderText="7-II" />
<asp:BoundField DataField="8_1" HeaderText="8-I" />
<asp:BoundField DataField="8_2" HeaderText="8-II" />
<asp:BoundField DataField="open" HeaderText="Open" />
<asp:BoundField DataField="score" HeaderText="Score" />
</Columns>
</asp:GridView>
ToggleEditMode checks if it should save or not, runs a SQL query if it should save, and calls toggleEditMode().
EDIT 2: Here is where toggleEditMode() is called. Sorry for the confusion. It's not called anywhere else.
protected void ToggleEditMode(object sender, EventArgs e)
{
if (editBtn.Attributes["mode"].ToString() == "save")
{
StringBuilder query = new StringBuilder();
List<SQLParameter> parameters = new List<SQLParameter>();
//Determine the year
int year;
int.TryParse(selectYear.SelectedItem.Value, out year);
parameters.Add(new SQLParameter("#year", year));
// Use a counter so we can enumerate parameter names
int i = 0;
foreach (GridView gv in panels)
{
foreach (GridViewRow gvr in gv.Rows)
{
TextBox name = (TextBox)gvr.FindControl("nameTB");
DropDownList rating = (DropDownList)gvr.FindControl("ratingDDL");
name.CssClass = "form-control green";
//SQL statements here
parameters.Add(new SQLParameter(String.Format("#name{0}", i), name.Text));
parameters.Add(new SQLParameter(String.Format("#schoolID{0}", i), name.Attributes["schoolID"].ToString()));
parameters.Add(new SQLParameter(String.Format("#rating{0}", i), rating.SelectedValue));
i++;
}
}
SqlConn.doQuery(query.ToString(), parameters);
//populateTables();
}
toggleEditMode();
}
Like #mjw mentioned in the comments, I was setting Enabled='false' in the markup. Due to the page life cycle, the controls were always rendering as Enabled='false'. If controls can be enabled/disabled based on conditions, this is best handled in the Page_Load function. However, ASP.NET has editing capabilities built into the GridView control, and these should be preferred over AJAX submissions for the inherent security benefits built into ASP.NET. Here are some links to get you started:
Making a column editable in an ASP.net GridView
https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/ms972948(v=msdn.10)

Filtering RadGrid by ComboBox

My problem is that when I try to click the combobox within my Radgrid, it doesn't do anything.
<telerik:RadGrid ID="RadGrid" runat="server" DataSourceID="TestReleaseInformationSource" ShowStatusBar="true"
OnItemCommand="RadGridItemCommand" OnPreRender="RadGrid_PreRender" AllowAutomaticUpdates="true" EnableLinqExpressions="false"
AllowAutomaticDeletes="true" AllowPaging="true" AutoGenerateColumns="false" AllowFilteringByColumn="true">
<MasterTableView DataKeyNames="PrimaryKey">
<Columns>
<telerik:GridBoundColumn AllowFiltering="true" UniqueName="TeacherLastName" DataField="TeacherLastName" HeaderText="Last Name">
<FilterTemplate>
<telerik:RadComboBox ID="radComboBoxLastName" DataSourceID="TeacherLastNameDDL" DataTextField="TeacherLastName" DataValueField="TeacherLastName"
AppendDataBoundItems="true" SelectedValue='<%# ((GridItem)Container).OwnerTableView.GetColumn("TeacherLastName").CurrentFilterValue %>'
runat="server" OnClientSelectedIndexChanged="TeacherLastNameChanged">
<Items>
<telerik:RadComboBoxItem Text="All" Selected="true" />
</Items>
</telerik:RadComboBox>
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function TeacherLastNameChanged(sender, args)
{
var tableView = $find("<%# ((GridItem)Container).OwnerTableView.ClientID %>");
tableView.filter("TeacherLastName", args.get_item().get_value(), "EqualTo");
}
</script>
</telerik:RadScriptBlock>
</FilterTemplate>
</telerik:GridBoundColumn>
On prerender of the grid
protected void RadGrid_PreRender(object sender, EventArgs e)
{
if (RadGrid.EditItems.Count > 0)
{
GridNestedViewItem item = (GridNestedViewItem)RadGrid.MasterTableView.GetItems(GridItemType.NestedView)[Convert.ToInt32(RadGrid.EditIndexes[0])];
item.Visible = false;
}
if (RadGrid.MasterTableView.FilterExpression != string.Empty)
{
RefreshCombos();
}
}
protected void RefreshCombos()
{
TestReleaseInformationSource.SelectCommand = TestReleaseInformationSource.SelectCommand + " WHERE " + RadGrid.MasterTableView.FilterExpression.ToString();
RadGrid.MasterTableView.Rebind();
}
I've stared at this for hours and can not figure out what the problem is. Any thoughts would be appreciated. Will post more code if necessary.
A solution I have found is to set the RenderMode property of the combobox to native. I would still like a different workaround.
Try making the JS functions unique: http://www.telerik.com/support/kb/details/using-dynamic-unique-names-for-javascript-functions
I think that all of them override each other so only the last one is active so only that executes. Also, look for JS errors.
Also, try invoking the filtering from the client as shown here http://www.telerik.com/help/aspnet-ajax/grid-client-side-binding-adding-sort-filter-expressions.html.
The masterTableView object is best obtained via the get_masterTableView() method of the main grid object.

Webdatagrid infragistics cant get the user control inside the cell

I have got a infragistics webdatagrid in my page, and on top of that page, i have got a webdatamenu with 2 buttons, one for refreshing the page, and the other for save the data from the grid.
What i am doing is a day scheduler.
here is my webdatagrid..
<ig:WebDataGrid ID="WebDataGridPlaneamentoHorarios" Visible="false" runat="server" Height="500px"
AutoGenerateColumns="False" Width="1300px" BorderColor="#666666"
ShowFooter="True" EnableDataViewState="True" >
<Columns>
<ig:BoundDataField DataFieldName="Numero" Key="Numero" Width="100px" Hidden="false">
<Header Text="Número" />
</ig:BoundDataField>
<ig:BoundDataField DataFieldName="Nome" Key="Nome" Width="100px">
<Header Text="Nome" />
</ig:BoundDataField>
<ig:BoundDataField DataFieldName="Descricao" Key="Descricao" Width="150px" Hidden="false">
<Header Text="Profissão" />
<Footer TemplateId="footerTemplate" />
</ig:BoundDataField>
<ig:TemplateDataField Key="Segmentos" Width="1510px" Hidden="False">
<ItemTemplate>
<uc1:Segmento ID="Segmento1" runat="server" />
</ItemTemplate>
<HeaderTemplate >
<uc5:HeaderControl ID="SegHed" runat="server"/>
</HeaderTemplate>
<FooterTemplate >
<div id="Quant" runat="server"> <uc2:SegNecessidades ID="SegNecessidades" runat="server" /></div>
<br /><br /> <div id="Totais" runat="server"><uc2:SegNecessidades ID="SegNecessidades2" runat="server" /></div>
<br /><br />
</FooterTemplate>
</ig:TemplateDataField>
<ig:BoundDataField DataFieldName="IDProfissao" Width="50px" Hidden="true" Key="IDProfissao">
<Header Text="IDProfissão" />
</ig:BoundDataField>
</Columns>
<Templates>
<ig:ItemTemplate ID="WebDataGridPlaneamentoHorariosTemplate2" runat="server"
TemplateID="footerTemplate">
<Template >
<uc3:FooterControl ID="FooterC" runat="server" />
</Template>
</ig:ItemTemplate>
</Templates>
</ig:WebDataGrid>
Everything is working fine, on refresh, the data is loaded...the problem is when i try to save the changes...
protected void WebDataMenuOptions_ItemClick(object sender, Infragistics.Web.UI.NavigationControls.DataMenuItemEventArgs e)
{
if (e.Item.Key == "btnRefrescar")
{
foreach (GridRecord row in WebDataGridPlaneamentoHorarios.Rows)
{
GridRecordItem itm = row.Items[3];
string id = row.Items[0].Text;
Control control = itm.FindControl("Segmento1");
DataTable DTblHorarioById = dbcHorariosEscalas.GetHorarioById(id, dt);
Segmentos seg = (Segmentos)control;
seg.AddSegmento(id, DTblHorarioById);
//this is to load the schedule of the user,,,,
}
}
else if(e.Item.Key == "btnGuardar")
{
foreach (GridRecord row in WebDataGridPlaneamentoHorarios.Rows)
{
GridRecordItem itm = row.Items[3];
string id = row.Items[0].Text;
Control control = itm.FindControl("Segmento1");
}
}
}
So the code is the same in both buttons, i am trying to find the user control called Segmento1, that is in the 4 column...
Now the code works when refresh button is pressed, the user control is found, but when i press the button save, the control is null...what is the problem...i am going nuts with this, because yesterday it was working, and then today it stoped, i think is one of those programming problems when the code works and stop working just because he wants..

Cannot unregister UpdatePanel with ID 'AjaxPanel' since it was not registered with the ScriptManager. This might occur if the

please I'm stock in this error and i can't get rid of it i have a user control inside another user control the child control contain RadAjaxPanel.
the parent control contain a Radgrid wish have an editformTemplate and the child control is loaded inside it i'll show u in code :
<EditFormSettings EditFormType="Template">
<EditColumn FilterControlAltText="Filter EditCommandColumn column">
</EditColumn>
<FormStyle BackColor="#FCFCFC"></FormStyle>
<FormTemplate>
<table>
<tr>
<td class="LblWidth" style="padding-top: 5px;">
<asp:Label ID="Label1" runat="server" Text="Center logo:">
</asp:Label>
</td>
<td style="padding-top: 10px;">
<uc1:MAYAUploadImageControl ID="UploadImageControl1" runat="server" />
<span class="redSpan">
</span>
</td>
</tr>
</table>
</FormTemplate>
</EditFormSettings>
that is the parent control
the child control is :
<telerik:RadAjaxPanel ID="ajaxPanel" runat="server" >
<asp:HiddenField ID="hf_FileName" runat="server" />
<asp:HiddenField ID="ImageChanged" runat="server" Value="0" />
<asp:Label ID="Label1" runat="server" Text="New Picture:"></asp:Label>
<br />
<telerik:RadImageEditor ID="RIEditor" runat="server" Width="180" Height="150" ToolBarMode="Default"
EnableResize="false" EnableTheming="false" BackColor="Transparent" OnImageSaving="ImageEditor_ImageSaving"
StatusBarMode="Hidden" CanvasMode="No" ToolBarPosition="top" BorderStyle="Solid"
BorderWidth="0px" Visible="false" OnClientImageLoad="ImageLoad" OnClientImageChanged="ImageChanged">
<Tools>
<telerik:ImageEditorToolGroup>
<telerik:ImageEditorTool CommandName="Flip" />
<telerik:ImageEditorTool CommandName="FlipVertical" />
<telerik:ImageEditorTool CommandName="FlipHorizontal" />
<telerik:ImageEditorToolSeparator />
<telerik:ImageEditorTool CommandName="Crop" />
<telerik:ImageEditorTool CommandName="Resize" />
<telerik:ImageEditorToolSeparator />
<telerik:ImageEditorTool CommandName="Reset" />
</telerik:ImageEditorToolGroup>
</Tools>
</telerik:RadImageEditor>
</telerik:RadAjaxPanel>
parent control ascx.cs:
protected void GridCenters_ItemCommand(object sender,Telerik.Web.UI.GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.UpdateCommandName || e.CommandName == RadGrid.PerformInsertCommandName)
{ controls_CustomControls_UploadImageControl_Maya ctrl = e.Item.FindControl("UploadImageControl1") as controls_CustomControls_UploadImageControl_Maya;
if (ctrl.ImageFileName != "")
{
//string imageFileName = (e.Item.FindControl("AsyncUpload1") as RadAsyncUpload).UploadedFiles[0].FileName;
ctrl.SaveImage();
logo = ctrl.ImageFileName != "" ? ConvertImgToBinary(ctrl.ImageFileName) : null;
}
switch (e.CommandName)
{
case "Update":
if(!EntertainmentDataAccess.UpdateCenter(long.Parse(e.CommandArgument.ToString()), centerName, centerType, logo, website, "", isactive, "", mail, tel, Mobile, fax, country, casa, town, street, BuildNb, POB))
{
LblError.Text = "Branch cannot be updated";
}
else
{
LblError.Text = "Branch updated successfully";
GridEditCommandColumn editColumn = (GridEditCommandColumn)GridCenters.MasterTableView.GetColumn("EDIT");
editColumn.Visible = true;
GridCenters.DataBind(); // here i'm getting the error
}
break;
}
}
I'm sorry for my messy explanation but i'm stuck for days in this problem and i cldn't resolve it
Based on the info in the links below, it looks like the RadAjaxPanel is being moved or removed from the Control Collection it belongs to. The third link contains a Telerik-specific workaround.
What causes the 'Cannot unregister UpdatePanel' error?
"Cannot unregister UpdatePanel with ID 'xxx' since it was not registered with the ScriptManager... " in RadGrid while editing record
http://www.telerik.com/support/kb/aspnet-ajax/window/cannot-unregister-updatepanel-with-id-updatepanelid-since-it-was-not-registered-with-the-scriptmanager.aspx
http://msmvps.com/blogs/luisabreu/archive/2006/11/16/adding-removing-updatepanels-dynamicaly-from-a-page.aspx

stop double postback

Here is what I am doing. I create two buttons in a header row of a gridview that i created. The buttons are +page and -page. When -page is hit I remove the paging and all the data goes down the page and -page disappears and +page is there.
Here comes my issue When I hit +page I must be double postbacking because one row of my data disappears. I will provide the code below. What can i do to fix this??
Dim bttnrempag As New Button
bttnrempag.ID = "bttnrempag"
bttnrempag.Text = " Paging"
bttnrempag.CssClass = "bttnMinEG"
bttnrempag.ValidationGroup = "alone"
bttnrempag.Attributes.Add("onclick", "return Paging('1')")
Dim bttnallowpag As New Button
bttnallowpag.ID = "bttnallowpag"
bttnallowpag.Text = " Paging"
bttnallowpag.ValidationGroup = "alone"
bttnallowpag.CssClass = "bttnAddEG"
bttnallowpag.Attributes.Add("onclick", "return Paging('0')")
---------------------How the buttons are added------------------------------------------
Dim row As New GridViewRow(-1, -1, DataControlRowType.Separator, DataControlRowState.Normal)
row.Cells.Add(cell)
cell.Controls.Add(bttnrempag) '36
cell.Controls.Add(bttnallowpag)
----------------------------------------------------------------------------------------
function Paging(remove) {
var gridView = $get('<%=Gridview1.ClientID %>');
var txt2 = $get('<%=TextBox2.ClientID %>');
if (remove == '1') {
txt2.value = '1';
__doPostBack('<%=UpdatePanel1.ClientID %>', '');
return false;
}
else {
txt2.value = '0';
__doPostBack('<%=UpdatePanel1.ClientID %>', '');
return false;
}
Edited
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate >
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#E7E7FF"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
DataSourceID="SqlDataSource1" Font-Names="Comic Sans MS" Font-Size="XX-Small"
Caption = '<table border="" width="100%" cellpadding="3" cellspacing="0" bgcolor="#4A3C8C"><tr><td style = "font-size:X-large;font-family:Arial CE;color:White"><b>Ordering/Receiving Log</u></td></tr></table>'
Font-Bold="True" PageSize="15" >
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<Columns>
Bound Data
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<EmptyDataTemplate>
<head>
<meta http-equiv="refresh" content="5;URL=/Corporate_newpo/ReceivingLog.aspx?">
</head>
<script type="text/javascript" >
var count = 6;
var counter = setInterval("timer()", 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
//counter ended, do something here
return;
}
$get("timer").innerHTML = "The Table will Reload in " + count + " secs";
}
</script>
<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="Large"
ForeColor="#993333" Text="No Data was Found for the Selected Filter"></asp:Label><br /><br />
<span id="timer" style="font-size:medium;color:blue"></span>
</EmptyDataTemplate>
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingRowStyle BackColor="#F7F7F7" />
<PagerTemplate>
<small 12px""="" style="font-size:xx-small; padding-right">Go To Page</small>
<asp:DropDownList ID="ddlPageSelector" runat="server" AutoPostBack="true"
Font-Size="XX-Small" Height="19px" Width="36px">
</asp:DropDownList>
<asp:ImageButton ID="btnFirst" runat="server" CommandArgument="First"
CommandName="Page" SkinID="pagefirst" />
<asp:ImageButton ID="btnPrevious" runat="server" CommandArgument="Prev"
CommandName="Page" SkinID="pageprev" />
<asp:ImageButton ID="btnNext" runat="server" CommandArgument="Next"
CommandName="Page" SkinID="pagenext" />
<asp:ImageButton ID="btnLast" runat="server" CommandArgument="Last"
CommandName="Page" SkinID="pagelast" />
</PagerTemplate>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
So as you can see, when one or the other is hit I set a textbox to some value then i do a partial postback to my Gridview which is in that Updatepanel.
I suspect it's because you called the "__doPostBack" method. The buttons' normal default click behaviour will perform the Async postback, you probably made it perform another time. Try removing it and see how it goes.
Can you try to put the Click Attribute on the buttons in RowDataBound event declaration??
Cheers.
Try changing your <asp:ImageButtons> to be regular HTML <img> tags.
I've run into this sort of thing before which was hard to diagnose and even harder to explain. See here and here for some buggy behavior that might help. If you have <img> tags with blank src attributes, then the hyperlinks I provided likely explain the problem. If you do not have any blank <img> tags then keep reading for my work around.
In my specific case, it was only happening on some servers (at some client sites) but not others, so I couldn't find any concrete issues with the code. My workaround was to change my <asp:ImageButtons> to regular <img> tags with javascript click events that would call a function to perform the postback, much like your Paging() function.
For some reason, I have found that an <asp:ImageButton> with a client side onclick event of return:confirm('are you sure?'); will stop a postback if the confirm() returns false, however returning false the way you do in your Paging() function after manually calling a __doPostBack does not consistently stop the page from posting back a second time.
Please look at the html as it is rendered on the page:
Every time it's present
<img src=""/>
double postback can happen, for some browser...
This trouble could be resolved setting a default, blank, image for every button
<asp:ImageButton ImageUrl="~/Images/blank.gif"...>
Anyway, this command can be entered in Immediate Window if you put a breakpoint inside Page_Load and allow you to indentify the control that caused postback
Page.Request.Params["__EVENTTARGET"];
I've found a nice solution that works great. It does append it's own handler, but I guess that can be fixed too.
using System.Linq;
private void GridView_OnItemDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var buttons = e.Row.Cells.OfType<DataControlFieldCell>().SelectMany(item => item.Controls.OfType<ImageButton>());
foreach (ImageButton imageButton in buttons)
{
var argument = imageButton.CommandName + "$" + imageButton.CommandArgument;
imageButton.OnClientClick = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView, argument) + "; return false;";
}
}
}
Try this, (I don't know why you were using javascript):
bttnrempag.onclick += bttnrempag_Click;
protected void bttnrempag_Click(object sender, EventArgs e)
{
//handle the removal of paging or whatever.
}
You have to provide an image for your ImageButtons. Otherwise the HTML rendered will produce an <img src=""> tag and when this is rendered, it will cause a postback. Try it.

Categories

Resources