Having some problems with a solution that apparently works:
<script type="text/javascript" >
//following code utilizes jQuery 1.2.6
var prev = 0;
$(document).ready(
//DIV showing the message "Loading..." is hidden initially
//The message will be shown when records are fetched with AJAX
//when user has scrolled to the bottom of the DIV scrollbar
function() {
$(".divProgress").hide();
$(".divLeft").scroll(
function() {
//triggering point is when the difference of the heights of the TABLE
//and DIV match the DIV's scrollTop value
if ($('<%=grdPersonResults.ClientID %>').height() - this.scrollTop == $(this).height()) {
//progress bar
$(".divProgress").ajaxStart(function() {
$(this).show();
});
$(".divProgress").ajaxStop(function() {
$(this).hide();
});
//get last Order Id to track next fetch
var OrderIdLast = $('<%=grdPersonResults.ClientID %> tr:last').children("td:first").html();
//get last table row in order to append the new result set increment
var trLast = $('<%=grdPersonResults.ClientID %> tr:last');
if (parseInt(OrderIdLast, 10) > parseInt(prev, 10)) {
prev = OrderIdLast;
//make a async call to fetch the incremental results
$.post("AsyncHandler.ashx?lastOrderId=" + OrderIdLast, function(data) {
if (data != null) {
//append new result set to last row
trLast.after(data);
}
});
}
}
});
});
</script>
My Gridview is fairly simple:
<div class="divLeft">
<asp:GridView ID="grdPersonResults" AutoGenerateColumns="False" runat="server"
CellPadding="2" Width="100%" ForeColor="#333333" GridLines="None" BorderWidth="1px" BorderStyle="Solid"
BorderColor="Black" AllowSorting="True" CssClass="box-table-a">
<Columns>
<asp:HyperLinkField HeaderText="Name" SortExpression="NAME" DataNavigateUrlFields="EMPLOYEE_ID, COMPANY_ID, RNUM"
DataNavigateUrlFormatString="~/Admin/FinalizeEdit.aspx?id={0}&cid={1}&rnum={2}&action=EDIT" DataTextField="NAME" />
<asp:BoundField DataField="DESCRIPTION" HeaderText="Company" SortExpression="DESCRIPTION" />
<asp:BoundField DataField="SOURCE_ID" HeaderText="Source" SortExpression="SOURCE_ID" />
</Columns>
<FooterStyle CssClass="box-table-a" />
<RowStyle CssClass="box-table-a" />
<EditRowStyle CssClass="box-table-a" />
<SelectedRowStyle CssClass="box-table-a" />
<PagerStyle CssClass="box-table-a" />
<HeaderStyle CssClass="box-table-a" />
<AlternatingRowStyle CssClass="box-table-a" />
</asp:GridView>
</div>
<div class="divProgress">
Loading....
</div>
It doesn't ever seem to hit my AsyncHandler, not sure if my selectors are wrong since I'm using a Masterpage in ASP.net, but it seems to be picking up the elements.
change
if ($('<%=grdPersonResults.ClientID %>').height() - this.scrollTop == $(this).height()) {
to
if ($("#grdPersonResults").height() - this.scrollTop <= $(this).height()-2) {
Related
I would like to change my gridview data. My data type are integer, but I want to divide this data with 100 For example;
They must be;
200,00
100,00
50,00
I tried do this with OnCustomColumnDisplayText event but when I added this event it was working more than one. When open the page, many times was worked again and again. So many times I divided with 100. Can you help me, please? My codes below;
<dx:ASPxGridView ID="MainDataList" ClientInstanceName="mainDataDl" runat="server" CssClass="mainDataList"
AutoGenerateColumns="False" EnableRowsCache="false" OnDataBinding="MainDataList_DataBinding" Width="100%"
OnRowUpdating="MainDataList_RowUpdating" OnCustomColumnDisplayText="MainDataList_CustomColumnDisplayText" >
<ClientSideEvents Init="grid_Init" />
<SettingsAdaptivity AdaptivityMode="HideDataCells" HideDataCellsAtWindowInnerWidth="600"
AllowOnlyOneAdaptiveDetailExpanded="true" AllowHideDataCellsByColumnMinWidth="true" />
<EditFormLayoutProperties>
<SettingsAdaptivity AdaptivityMode="SingleColumnWindowLimit" SwitchToSingleColumnAtWindowInnerWidth="680" />
</EditFormLayoutProperties>
<SettingsEditing Mode="EditFormAndDisplayRow" EditFormColumnCount="2"/>
<Styles>
<Header ForeColor="White" BackColor="#969696" Font-Size="12px" />
<Cell Font-Size="12px" Wrap="False" />
<EditForm CssClass="editForm" />
</Styles>
<Settings ShowFilterRow="True" AutoFilterCondition="Contains" />
<Columns>
<dx:GridViewCommandColumn ShowClearFilterButton="True" VisibleIndex="0" Name="TempColumn" >
</dx:GridViewCommandColumn>
</Columns>
<SettingsPager PageSize="10" NumericButtonCount="4" Mode="ShowPager" />
<TotalSummary />
<SettingsDataSecurity AllowDelete="False" AllowEdit="True" AllowInsert="False" />
<SettingsSearchPanel Visible="false" CustomEditorID="MainDataListSearchTextBox" />
<SettingsLoadingPanel Mode="Disabled" />
<SettingsBehavior AllowFocusedRow="True" ProcessFocusedRowChangedOnServer="true" />
<SettingsCommandButton>
<ShowAdaptiveDetailButton ButtonType="Image">
</ShowAdaptiveDetailButton>
<HideAdaptiveDetailButton ButtonType="Image">
</HideAdaptiveDetailButton>
</SettingsCommandButton>
</dx:ASPxGridView>
protected void MainDataList_CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e)
{
foreach (MimasPortal.TableFieldData_1_0 tf in userSession.DetailStruct.Fields)
{
if (tf.FieldType == "MONEY")
{
DataRowView rowData = (DataRowView)MainDataList.GetRow(e.VisibleIndex);
if (rowData != null)
{
if (rowData.Row[tf.FieldName].ToString().Length > 2 && rowData.Row[tf.FieldName].ToString().IndexOf('.') < 1 && rowData.Row[tf.FieldName].ToString().IndexOf(',') < 1)
{
decimal newValue = (Convert.ToDecimal(e.GetFieldValue(tf.FieldName))) / 100;
rowData.Row[tf.FieldName] = newValue;
}
else
{
rowData.Row[tf.FieldName] = e.GetFieldValue(tf.FieldName).ToString();
}
}
}
}
}
so i have a grid view like this :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="VideoID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="VideoID" HeaderText="VideoID" ReadOnly="True" InsertVisible="False" SortExpression="VideoID" Visible="false"></asp:BoundField>
<asp:BoundField DataField="VideoEpisodeNumber" HeaderText="Episode" SortExpression="VideoEpisodeNumber"></asp:BoundField>
<asp:HyperLinkField DataTextField="VideoUrl" HeaderText="Video Url" DataTextFormatString="Link"/>
<asp:BoundField DataField="VideoDescription" HeaderText="VideoDescription" SortExpression="VideoDescription"></asp:BoundField>
</Columns>
</asp:GridView>
the hyperlinkfield is supposed to have the video links! how can i retrieve that link when a user click on it?
thank you in advance
You can try this:
<asp:HyperLinkField DataTextField="VideoUrl" HeaderText="Video Url" DataTextFormatString="Link" onclick="javascript:GetURL(this);"/>
function GetURL(sender) {
//Possibly sender should contain the object.
//if not
var parent = $find(sender.id);
var linkURL = parent.innerHTML;
}
When you are propagating DataNavigationUrlFields the href attribute will be set. Then you should be able to intercept the navigation to the corresponding video url (assuming that resolving the url on the client is what you are looking for)
Gridview
<asp:HyperLinkField DataTextField="VideoUrl" HeaderText="Video Url" NavigateUrl="http://wwww.youtube.com" />
Javascript (jquery)
$(function () {
$("#myGridviewId a").on("click", interceptNavigation);
});
function interceptNavigation() {
alert($(this).attr("href"));
}
I've scoured the web looking at the various examples and have tried every single one of them. I get the same error no matter what. I am trying to add the headerrow to the GridView control in code. I have tried adding the below code in every possible event from gridview prerender to all of the events of the page. Same deal. Always get the error: The table must contain row sections in order of header, body, then footer.
I have stripped down the page to the bare essentials - removing the master page and all CSS.
Here is the aspx and grid view code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Shipping.Admin.Default" Title="Apps - Shipping" %>
<html>
<head><title></title></head>
<body>
<form runat="server" id="form1">
<br />
<h1>Admin Page</h1>
<br />
<asp:GridView ID="gvShipments" runat="server" AllowSorting="True"
AutoGenerateColumns="False" onsorting="gvShipments_Sorting" Width="100%"
AllowPaging="True" onpageindexchanging="gvShipments_PageIndexChanging"
PageSize="50">
<PagerSettings Position="TopAndBottom" />
<Columns>
<asp:BoundField DataField="RequestDate" HeaderText="Request Date" SortExpression="dtRequestDate" />
<asp:BoundField DataField="Requestor" HeaderText="Requestor" SortExpression="Requestor" />
<asp:BoundField DataField="CompanyName" HeaderText="Company" SortExpression="CompanyName" />
<asp:BoundField DataField="ShipmentDescription" HeaderText="Description" SortExpression="ShipmentDescription" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="State" HeaderText="State" SortExpression="State" />
<asp:BoundField DataField="ShipmentType" HeaderText="Shipment Type" SortExpression="ShipmentType" />
<asp:BoundField DataField="ServiceLevel" HeaderText="Service Level" SortExpression="ServiceLevel" />
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
<asp:HyperLinkField DataNavigateUrlFields="ShipmentId" DataNavigateUrlFormatString="Shipment.aspx?CatId=Admin&sID={0}" Text=" edit" />
</Columns>
</asp:GridView>
<br />
</form>
</body>
</html>
Here is a snipped of the code-behind. This method is called in the Page_Load method:
private void LoadGridView()
{
DataSet ds = new DataSet();
ds = GetDataset();
DataTable dtRequests = ds.Tables["Admin"];
DataView dv = new DataView(dtRequests);
if (ViewState["sortexpression"] != null)
{
dv.Sort = ViewState["sortexpression"].ToString() + " " + ViewState["sortdirection"].ToString();
}
else
{
dv.Sort = "dtRequestDate DESC";
}
gvShipments.DataSource = dv;
gvShipments.DataBind();
**if (gvShipments.Rows.Count > 0)
{
this.gvShipments.UseAccessibleHeader = true;
this.gvShipments.HeaderRow.TableSection = TableRowSection.TableHeader;
}**
ds.Dispose();
}
I have tried adding the code inside bolded the IF statement everywhere. I am stumped. Please help!
Thanks
Try this add Page_PreRender event and post your code inside it, then your code look like as below
protected void Page_PreRender(object sender, EventArgs e)
{
if (gvShipments.Rows.Count > 0)
{
gvShipments.UseAccessibleHeader = true;
gvShipments.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
PageLifeCycle
i have gridview with lots of records, so had to use ObjectDataSource so as to fetch only the records that will be displayed on the page i.e. if there are total 100 records, and page size is 10, on each page click only 10 records are fetched from DB.
Please find the code below
///aspx
<asp:GridView ID="grdModulesList" CssClass="moduleList" runat="server"
AutoGenerateColumns="False" HeaderStyle-Font-Size="Smaller"
Font-Size="Small" AllowPaging="true" AllowSorting="True" OnRowCreated="grdModulesList_RowCreated"
OnRowDataBound="grdModulesList_RowDataBound" BackColor="White" BorderColor="Blue"
BorderStyle="None" BorderWidth="1px" CellPadding="3" PageSize="20">
<Columns>
<asp:BoundField DataField="collection_id" Visible="False" />
<asp:BoundField HeaderText="Item" />
<asp:BoundField HeaderText="Module Name" DataField="module_name" SortExpression="module_name"
ControlStyle-CssClass="moduleName" />
<asp:BoundField HeaderText="File Name" DataField="module_file_name" SortExpression="module_file_name" />
<asp:BoundField HeaderText="ID" DataField="defect_number" SortExpression="defect_number" />
<asp:BoundField HeaderText="Actions" />
</Columns>
<RowStyle BorderColor="Blue" BorderStyle="Solid" CssClass="grid_width" BorderWidth="2px"
Height="20px" />
<PagerStyle BackColor="#FFFF99" ForeColor="Red" HorizontalAlign="Center" Height="20px" />
<FooterStyle ForeColor="black" Font-Bold="true" />
<SelectedRowStyle Font-Size="Smaller" />
<HeaderStyle Font-Size="Smaller" BorderStyle="Solid" BackColor="Gold" Font-Bold="True"
ForeColor="Black" Height="30px" />
<AlternatingRowStyle BorderColor="#3366FF" BorderStyle="Solid" BorderWidth="1px" />
</asp:GridView>
//.aspx.cs
ObjectDataSource ods = new ObjectDataSource();
ods.ID = "ods";
ods.SelectMethod = "GRAD_ModuleListforCollection_Subset"; //method to fetch records from DB
ods.EnablePaging = true;
ods.TypeName = "pmAdmin.classes.data.ApplicationData";
ods.StartRowIndexParameterName = "StartRecord";
ods.MaximumRowsParameterName = "PageSize";
ods.SortParameterName = "SortBy";
ods.SelectCountMethod = "GRAD_Total_Modules";
Parameter p1 = new Parameter("userID", TypeCode.String, userId);
ods.SelectParameters.Add(p1);
panelModuleList.Controls.Add(ods); //add objectDatasource control to a panel
grdModulesList.DataSourceID = ods.ID;
grdModulesList.DataBind();
//method GRAD_ModuleListforCollection_Subset
public System.Data.DataSet GRAD_ModuleListforCollection_Subset(string userID, int StartRecord, int PageSize, string SortBy)
{}
records are correctly binded to Gridview, but the issue is the method used to fetch the records from DB i.e.GRAD_ModuleListforCollection_Subset is called twice for each click on page.
example : if i click on page 2 the method is called
() first time with startRecord=0,pagesize=20
() called second time with startRecord=20,pagesize=20
after click on page 2 if i click page 3
() first time with startRecord=20,pagesize=20
() called second time with startRecord=40,pagesize=20
for every page click, first load is having previous value.
Kindly help me in resolving this.
Thanks in advance.
made the following changes to make it work
enable caching for objectDatasource
ods.EnableCaching = true;
set Session["sortorder"]
grdModulesList.DataSourceID = ods.ID;
grdModulesList.DataBind();
if (Session["sortorder"] == null)
Session["sortorder"] = "Ascending";
add gridview sorting event
protected void grdModulesList_Sorting(object sender, GridViewSortEventArgs e)
{
ods.SelectParameters["SortBy"].DefaultValue = GetSortExpr(e.SortExpression);
e.Cancel = true; //We have to do this or we will get an exception
}
public string GetSortExpr(string sortExp)
{
if (Session["sortorder"].ToString() == "Ascending")
{
Session["sortorder"] = "Descending";
return sortExp + " DESC";
}
else
{
Session["sortorder"] = "Ascending";
return sortExp + " ASC";
}
}
if you declare the ObjectDataSource and all its setting in Markup portion (.aspx), then the Select method is called twice only when page is requested for very first time ( PageIndex defaults to 1).
when you select page 2 from paging links, it will call only once the select method then the SelectCount method.
I have binded a custom datatable to gridview. Now I want to validate if the value of cells of the column "DocumentsAttached" is Yes or No. If it is yes, then an alert message displaying " Documents are Attached". If No, a pop up box with message would you like to continue" Yes/No...If yes, is chosen my submit button should go through otherwise no.
Hope i made sense until now. Below is my aspx
<asp:GridView ID="UploadDocs" AutoGenerateColumns="False" runat="server"
EnableViewState="true" onrowdatabound="dgdUpload_RowDataBound" style="margin-top: 0px">
<Columns>
<asp:HyperLinkField DataTextField="DocName" HeaderText="Invoice File Name" DataNavigateUrlFields="FilePath" DataNavigateUrlFormatString="{0}">
</asp:HyperLinkField>
<asp:BoundField HeaderText="Document Included" DataField="DocumentsAttached" ReadOnly="true" />
<asp:BoundField HeaderText="Identifier" DataField="Identifier" Visible="false"/>
<asp:CommandField ButtonType="Button" HeaderText="Delete" ShowDeleteButton="true"/>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Save to MassUploadList" />
Can anyone help me to achieve this please.
Replace <asp:BoundField HeaderText="Document Included" DataField="DocumentsAttached" ReadOnly="true" /> with this:
<asp:TemplateField HeaderText="Document Included" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblDocumentsAttached" runat="server" Text='<%# Eval("DocumentsAttached")%>' CssClass="DocumentsAttached"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
and use this javascript to validate:
function validateAttachment() {
$(".DocumentsAttached").each(){
if($(this).val().toLowerCase()=="no") {
return false;
}
}
return true;
}
But validation this way is not a good idea since I can easily bypass it by just changing the column values in the DOM using firebug.
I would assume you're uploading something, or otherwise generating the datatable from codebehind. So why not do server side validation? If at least one row has DocumentAttached equal to "NO", disable submit button and add a custom validator to the page with relevant message.
The function that I used to serve my purpose is below
<script language="javascript" type="text/javascript">
function Validate() {
var cntrlname = document.getElementById('<%= gridview1.ClientID %>');
var gridcell;
var retVal = 1;
var result = 1;
for (i = 1; i < cntrlname.rows.length; i++) {
if (cntrlname.rows[i].cells[2].innerText == "No") {
retVal = 0;
}
if (retVal == 0) {
return window.confirm("One of the Attachments is missing, would you like to proceed")
}
else{
return true;
}
}
}
function window.confirm(str) {
execScript('n = msgbox("' + str + '","4132")', "vbscript");
return (n == 6);
}
The column documents attached is readonly, the user will not be able to make any changes to it.So , this displays a confirmation box if there any attachments missing, if the user is ok ...it will execute the server side code otherwise will not.