How to apply javascript on SelectedIndexChanging of grid view - asp.net

I have wriiten a javascript which I am using it onblur event of textbox which is inside a gridview. The same script should fire for me when I perform SelectedIndexChanging of gridview. This is my script
<script type="text/javascript">
function total(txtQuantity, txtRate, txtAmount) {
var col1;
var totalcol1 = 0;
var weight = document.getElementById(txtQuantity).value;
var rate = document.getElementById(txtRate).value;
var tot = weight * rate;
document.getElementById(txtAmount).value = tot.toFixed(2).toString();
var grid = document.getElementById('<%=grdInvoice.ClientID %>');
for (i = 0; i < grid.rows.length; i++) {
col1 = grid.rows[i].cells[4];
//col2 = grid.rows[i].cells[1];
for (j = 0; j < col1.childNodes.length; j++) {
if (col1.childNodes[j].type == "text") {
if (!isNaN(col1.childNodes[j].value) && col1.childNodes[j].value != "") {
totalcol1 += parseInt(col1.childNodes[j].value)
}
}
}
}
document.getElementById('<%= lblTotal.ClientID %>').innerHTML = totalcol1.toFixed(2).toString();
document.getElementById('<%=lblResultbalance.ClientID%>').innerHTML = totalcol1.toFixed(2).toString();
document.getElementById('<%=TextBox1.ClientID%>').value = totalcol1.toFixed(2).toString();
}
Can some one help me

Try this in your event
ScriptManager.RegisterStartupScript(this, GetType(), "script", "total('" + txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "')", true);

Related

Error: Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation

I want to display Agendas from table "tblAgenda" using Asp.net here is the query:
public static List<int> SelectByYear()
{
DbManager db = new DbManager();
try
{
List<int> list = new List<int>();
var result = from p in db.tblAgenda
group p by p.News.Value.Year
into g
select new { Year = g.Key, Releases = g };
foreach (var obj in result)
{
list.Add(obj.Year);
}
list.Reverse();
return list.ToList<int>();
}
catch
{
return null;
}
finally
{
db.Dispose();
}
}
and here I am calling the above method:
public partial class edd_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Request.QueryString["id"]))
{
RecentData();
}
}
}
private void RecentData()
{
List<tblAgenda> agd = new List<tblAgenda>();
StringBuilder sbHeadings = new StringBuilder();
StringBuilder sbData = new StringBuilder();
List<int> list1 = AgendaManager.SelectByYear();
if (list1 != null)
{
List<int> list = list1.Take(3).ToList<int>();
int Row = 0;
string RowCss = "";
foreach (tblAgenda ob in agd)
{
strYears = "";
if (list.Count > 0)
{
Table tblHead = new Table();
TableRow trHead = new TableRow();
TableCell tcDvHead = new TableCell();
TableCell tcLnkHead = new TableCell();
for (int i = 0; i < list.Count; i++)
{
Row = 0;
List<clsAgenda> listData = new List<clsAgenda>();
listData = null;
DateTime dt = DateTime.Now.AddYears(1);
string stryr = strYears;
int intyr = Convert.ToInt32(list[i]);
diff = Convert.ToInt32(dt.Year) - Convert.ToInt32(intyr);
if (diff == 0 || diff == 1 || diff == 2)
{
if (drpDepartments.SelectedValue == "-1")
{
strYears += list[i] + ",";
sbHeadings.Append("<div id='dv" + list[i] + "' style='float:left;width:60px;cursor:pointer;' class='btnclass11'>" + list[i] + "</div><div style='float:left;'> </div>");
listData = AgendaManager.SelectAllByYear(Convert.ToInt32(list[i]));
}
else
{
if (AgendaManager.IsAgendExistForDeptartment(Convert.ToInt32(list[i]), Convert.ToInt64(drpDepartments.SelectedValue)))
{
strYears += list[i] + ",";
sbHeadings.Append("<div id='dv" + list[i] + "' style='float:left;width:60px;cursor:pointer;' class='btnclass11'>" + list[i] + "</div><div style='float:left;'> </div>");
}
listData = AgendaManager.SelectAllByYear(Convert.ToInt32(list[i]), Convert.ToInt64(drpDepartments.SelectedValue));
}
sbData.Append("<table id='tbl" + list[i] + "' cellspacing='1' cellpadding='4' width='885' style='display:none;margin-top:10px;' class='GridBorder' >");
sbData.Append("<tr class='GridViewHeaderStyle' >");
sbData.Append("<th style='width:380px;height:22px;text-align:left;'>Meeting</th><th style='height:22px;text-align:left;'>Date</th><th style='width:70px;height:22px;text-align:left;'>Time</th><th style='width:70px;height:22px;text-align:left;'>Agenda</th><th style='height:22px;text-align:left;width:120px;'>Web Cast</th><th style='height:22px;text-align:left;width:100px;'>Minutes</th>");
sbData.Append("</tr>");
foreach (clsAgenda obj in listData)
{
RowCss = "";
if (Row == 1)
{
RowCss = "class='GridRow'";
}
sbData.Append("<tr " + RowCss + ">");
sbData.Append("<td >" + obj.Title + "</td>");
sbData.Append("<td >" + string.Format("{0:MMM dd, yyyy}", obj.AgendaDate) + "</td>");
sbData.Append("<td >" + obj.Time + "</td>");
sbData.Append("<td ><a style='color:black;' href='agenda.aspx?id=" + obj.ID + "'>View</a></td>");
if (string.IsNullOrEmpty(obj.WebCast))
{
sbData.Append("<td >---</td>");
}
else
{
sbData.Append("<td ><a style='color:black;' href='" + obj.WebCast + "'>" + obj.WebCastTitle + "</a></td>");
}
if (string.IsNullOrEmpty(obj.MinutesFile))
{
sbData.Append("<td >---</td>");
}
else
{
if (ob.showThroughBroswer == 1)
{
sbData.Append("<td ><a href='downloadfile.aspx?AgendaMinuteId=" + obj.ID + "' target='_blank'>View</a></td>");
}
else
{
sbData.Append("<td ><a href='showpdf.aspx?AgendaMinuteId=" + obj.ID + "' target='_blank'>View</a></td>");
}
}
sbData.Append("</tr>");
Row++;
if (Row == 2)
{
Row = 0;
}
}
sbData.Append("</table>");
}
else
break;
}
if (strYears.Length > 0)
{
strYears = strYears.Substring(0, strYears.Length - 1);
}
strFirstYear = list[0].ToString();
tcDvHead.Text = sbHeadings.ToString();
if (diff == 1 || diff == 2)
{
tcLnkHead.Text = "<div class='dvhrfclass'><a href='listagendas.aspx?id=pre' class='link1'>Previous Meetings >></a></div>";
}
else
{
tcLnkHead.Text = "";
}
trHead.Cells.Add(tcDvHead);
trHead.Cells.Add(tcLnkHead);
tblHead.Rows.Add(trHead);
StringWriter sW = new StringWriter();
HtmlTextWriter hW = new HtmlTextWriter(sW);
tblHead.RenderControl(hW);
letHeading.Text = sW.ToString();
letData.Text = sbData.ToString();
}
}
}
}
now the issue is I am getting no values in list1, I have tried using the debugger on the query and found that I can't access the "tblAgenda", its giving an error that: " Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation". I have searched alot but didn't find anything good, my connection string is totally fine because all the other tables are working fine even in "tblAgenda" I can store new agenda from admin panel but I can't retrieve the agendas on front end, what is the issue here?
Thanks.

Find radio button control in nested repeater control in asp.net?

I have two repeater controls one inside other and in inner repeater there is placeholder in which radio button is dynamically generated. I want to find the radio button control to check whether it is checked or not? I want above all function to be performed in button submit/click event defined in the code?
if (!Page.IsPostBack)
{
//1) Load SomeDatatable from Database somehow
// Just for testing : replace with query to DB
strqry = "select * from Quiz_tblQsnsLimitMaster where Qsnexamname='" + Request.QueryString["QsnEname"].ToString() + "'";
SqlDataAdapter adp = new SqlDataAdapter(strqry, sCon);
DataSet ds = new DataSet();
try
{
adp.Fill(ds);
int total = ds.Tables[0].Rows.Count;
for (int i = 0; i < total; i++)
{
string QuesID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
//SubName = ds.Tables[0].Rows[i].ItemArray[3].ToString();
DataSet oDs = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_OnlineTest_QuestionsWithOptions_Get", QuesID);
SomeDatatable.Merge(oDs.Tables[0]);
}
removeDuplicatesRows(SomeDatatable);
System.Data.DataColumn newColumn = new System.Data.DataColumn("ContentIndex", typeof(System.String));
newColumn.DefaultValue = "0";
SomeDatatable.Columns.Add(newColumn);
for (int i = 0; i < Math.Ceiling((decimal)SomeDatatable.Rows.Count); i++)
SomeDatatable.Rows[i]["ContentIndex"] = i + 1;
}
catch
{
}
////2) Create a dummy data source for the tab repeater using a list of anonymous types
List<object> TabList = new List<object>();
//BindSubject();
for (int I = 0; I < Math.Ceiling((decimal)SomeDatatable.Rows.Count / (decimal)ContentPerTab); I++)
{
TabList.Add(new { TabIndex = I });
}
TabRepeater.ItemDataBound += TabRepeater_ItemDataBound;
TabRepeater.DataSource = TabList;
TabRepeater.DataBind();
//TablLinkRepeater.DataSource = TabList;
//TablLinkRepeater.DataBind();
//}
}
public void removeDuplicatesRows(DataTable dt)
{
SomeDatatable = dt.DefaultView.ToTable(true, "QuestionId");
}
protected void TabRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
int TabIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "TabIndex").ToString(), out TabIndex);
//Copy Content Rows from SomeDatable that belong to this tab
DataTable Dt = SomeDatatable.Clone();
for (Int32 i = TabIndex * ContentPerTab; i <= (TabIndex + 1) * ContentPerTab - 1; i++)
{
if (i >= SomeDatatable.Rows.Count) break;
Dt.ImportRow(SomeDatatable.Rows[i]);
}
// Find the content repeater in this item and use the new datatable as source
Repeater ContentRepeater = (Repeater)e.Item.FindControl("ContentRepeater");
ContentRepeater.ItemDataBound += ContentRepeater_ItemDataBound;
ContentRepeater.DataSource = Dt;
ContentRepeater.DataBind();
}
}
// This handler might be needed for content repeater, included just for testing
protected void ContentRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
//Read coulmn from Datarow
int ContentIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "ContentIndex").ToString(), out ContentIndex);
var parsed = "'" + HttpUtility.ParseQueryString(DataBinder.Eval(e.Item.DataItem, "QuestionID").ToString()) + "'";
//Add Question
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get", Convert.ToString(parsed));
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
int iCnt = 0;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Table tblQsn = new Table();
//.....Begin Text Qsn Creation.....//
tblQsn.Width = new Unit("98%");
TableRow trQsn = new TableRow();
iRowCounter++;
trQsn.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsn = new TableCell();
TableCell tcQsnSNo = new TableCell();
tcQsn.CssClass = "Label";
tcQsn.BackColor = System.Drawing.Color.Gainsboro;
tcQsn.Font.Bold = true;
tcQsn.Font.Size = 12;
tcQsn.Text = ds.Tables[0].Rows[i][1].ToString();
tcQsn.Width = Unit.Percentage(99.5);
iCellCounter++;
tcQsn.ID = "Cell_" + iCellCounter.ToString();
tcQsnSNo.CssClass = "Label";
tcQsnSNo.Attributes.Add("valign", "top");
tcQsnSNo.BackColor = System.Drawing.Color.Gainsboro;
tcQsnSNo.Font.Bold = true;
tcQsnSNo.Width = Unit.Percentage(0.5);
iCellCounter++;
tcQsnSNo.ID = "Cell_" + iCellCounter.ToString();
iCnt++;
tcQsnSNo.Text = ContentIndex.ToString() + ".";
trQsn.Cells.Add(tcQsnSNo);
trQsn.Cells.Add(tcQsn);
tblQsn.Rows.Add(trQsn);
int rcnt = i;
int iOptCnt = 0;
string sStatus = "N";
while ((rcnt >= 0) && (rcnt < ds.Tables[0].Rows.Count))
{
if (ds.Tables[0].Rows[rcnt][2].ToString() == ds.Tables[0].Rows[i][2].ToString())
{
if (sStatus == "N")
{
sStatus = "Y";
}
TableRow trQsnOpt = new TableRow();
iRowCounter++;
trQsnOpt.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsnOpt = new TableCell();
tcQsnOpt.CssClass = "Label";
iCellCounter++;
tcQsnOpt.ID = "Cell_" + iCellCounter.ToString();
tcQsnOpt.Attributes.Add("valign", "top");
tcQsnOpt.VerticalAlign = VerticalAlign.Middle;
TableCell tcQsnOptSNo = new TableCell();
tcQsnOptSNo.CssClass = "Label";
iCellCounter++;
tcQsnOptSNo.ID = "Cell_" + iCellCounter.ToString();
iOptCnt++;
RadioButton oRbOptions = new RadioButton();
oRbOptions.GroupName = ds.Tables[0].Rows[rcnt][2].ToString() + "_Group";
oRbOptions.Text = ds.Tables[0].Rows[rcnt][3].ToString().Trim();
oRbOptions.Font.Size = 11;
iRbTCounter++;
oRbOptions.ID = ds.Tables[0].Rows[i][0].ToString() + "_" + ds.Tables[0].Rows[rcnt][2].ToString() + "_" + "Option" + iOptCnt.ToString() + "_" + iRbTCounter.ToString();
//oRbOptions.Enabled = false;
//if (ds.Tables[0].Rows[i][2].ToString() == "Option" + iRbTCounter.ToString())
//{
// oRbOptions.Checked = true;
//}
oRbOptions.InputAttributes.Add("data-info", Convert.ToString(ContentIndex));
oRbOptions.CssClass = "Label";
tcQsnOpt.Controls.Add(oRbOptions);
tcQsnOptSNo.Text = iOptCnt.ToString() + ".";
trQsnOpt.Cells.Add(tcQsnOptSNo);
trQsnOpt.Cells.Add(tcQsnOpt);
rcnt++;
//.....Add Option Image.....//
tblQsn.Rows.Add(trQsnOpt);
}
else
break;
}
i = rcnt - 1;
PlPreview = (PlaceHolder)e.Item.FindControl("PlPreview");
PlPreview.Controls.Add(tblQsn);
}
}
}
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
SubmitQuestion();
}
public void SubmitQuestion()
{
for (int c = 0; c < SomeDatatable.Rows.Count; c++)
{
string sQsnOptId = SomeDatatable.Rows[c]["QuestionID"].ToString();
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get", "'" + sQsnOptId + "'");
for (int i = 1; i <= 4; i++)
{
string rdboption = ds.Tables[0].Rows[c][0].ToString() + "_" + ds.Tables[0].Rows[i-1][2].ToString() + "_" + "Option" + i + "_" + i;
Repeater rpt = (Repeater)TabRepeater.NamingContainer.FindControl("ContentRepeater");
RadioButton rbt = (RadioButton)rpt.NamingContainer.FindControl(rdboption);
if (rbt.Checked)
{
strqry = "update Quiz_tblOnlineTest_Detail set UserAns='Option" + i + "', DeletionStatus='A' where CreationLogInId='AMITSAMBYAL#HOTMAIL.COM' and ExamName='" + Request.QueryString["QsnEname"].ToString() + "' and QsnId=" + Session["quesid"].ToString() + "";
cmd = new SqlCommand(strqry, con);
try
{
cmd.ExecuteNonQuery();
}
catch
{
}
finally
{
con.Close();
}
break;
}
}
}
}
}
I found the answer. Thanks
foreach (RepeaterItem repeater in TabRepeater.Items)
{
Repeater repeater1 = (Repeater)repeater.FindControl("ContentRepeater");
foreach (RepeaterItem repItem in repeater1.Items)
{
for (int i = 1; i <= 4; i++)
{
string rdboption = ds.Tables[0].Rows[c][0].ToString() + "_" + ds.Tables[0].Rows[i - 1][2].ToString() + "_" + "Option" + i + "_" + i;
PlaceHolder PlPreview = (PlaceHolder)repItem.FindControl("PlPreview");
rbt = (RadioButton)PlPreview.FindControl(rdboption);
if (rbt.Checked)
{
// statement
}
}
}
}
}
}

Updating existing fields in MS Access database through classic ASP

I've been given working ASP code which I have to change in order to update existing data in database insted of creating new entries. I think I should swap INSERT INTO statment with UPDATE but the code is a bit too coplicated for me to figure out where and what to change.
Here it comes:
// *** Edit Operations: declare variables
// set the form action variable
var MM_editAction = Request.ServerVariables("SCRIPT_NAME");
if (Request.QueryString) {
MM_editAction += "?" + Server.HTMLEncode(Request.QueryString);
}
// boolean to abort record edit
var MM_abortEdit = false;
// query string to execute
var MM_editQuery = "";
// *** Insert Record: set variables
if (String(Request("MM_insert")) == "AddRecord") {
var MM_editConnection = MM_PhoneWeb_conn_STRING;
var MM_editTable = "Employees";
var MM_editRedirectUrl = "userRegister.asp";
var MM_fieldsStr = "textSurname|value|textFirstname|value|textUsername|value|textPass|value";
var MM_columnsStr = "Surname|',none,''|FirstName|',none,''|Username|',none,''|Password|',none,''";
// create the MM_fields and MM_columns arrays
var MM_fields = MM_fieldsStr.split("|");
var MM_columns = MM_columnsStr.split("|");
// set the form values
for (var i=0; i+1 < MM_fields.length; i+=2) {
MM_fields[i+1] = String(Request.Form(MM_fields[i]));
}
// append the query string to the redirect URL
if (MM_editRedirectUrl && Request.QueryString && Request.QueryString.Count > 0) {
MM_editRedirectUrl += ((MM_editRedirectUrl.indexOf('?') == -1)?"?":"&") + Request.QueryString;
}
}
// *** Insert Record: construct a sql insert statement and execute it
if (String(Request("MM_insert")) != "undefined") {
// create the sql insert statement
var MM_tableValues = "", MM_dbValues = "";
for (var i=0; i+1 < MM_fields.length; i+=2) {
var formVal = MM_fields[i+1];
var MM_typesArray = MM_columns[i+1].split(",");
var delim = (MM_typesArray[0] != "none") ? MM_typesArray[0] : "";
var altVal = (MM_typesArray[1] != "none") ? MM_typesArray[1] : "";
var emptyVal = (MM_typesArray[2] != "none") ? MM_typesArray[2] : "";
if (formVal == "" || formVal == "undefined") {
formVal = emptyVal;
} else {
if (altVal != "") {
formVal = altVal;
} else if (delim == "'") { // escape quotes
formVal = "'" + formVal.replace(/'/g,"''") + "'";
} else {
formVal = delim + formVal + delim;
}
}
MM_tableValues += ((i != 0) ? "," : "") + MM_columns[i];
MM_dbValues += ((i != 0) ? "," : "") + formVal;
}
MM_editQuery = "insert into " + MM_editTable + " (" + MM_tableValues + ") values (" + MM_dbValues + ")";
if (!MM_abortEdit) {
// execute the insert
var MM_editCmd = Server.CreateObject('ADODB.Command');
MM_editCmd.ActiveConnection = MM_editConnection;
MM_editCmd.CommandText = MM_editQuery;
MM_editCmd.Execute();
MM_editCmd.ActiveConnection.Close();
if (MM_editRedirectUrl) {
Response.Redirect(MM_editRedirectUrl);

Fixed GridView Header with horizontal and vertical scrolling in asp.net

I want to fix(Freeze) gridview header while vertical scrolling.
I also want to fix first column while horizontal scrolling.
I want this in both chrome and IE.
It is possible to apply the specific GridView / Table layout via custom CSS rules (as it was discussed in the <table><tbody> scrollable? thread) to fix GridView's Header. However, this approach will not work in all browsers. The 3-rd ASP.NET GridView controls (such as the ASPxGridView from DevExpress component vendor provide this functionality.
Check also the following CodeProject solutions:
Fixed header Grid
Gridview with fixed header
Gridview Fixed Header
I was looking for a solution for this for a long time and found most of the answers are not working or not suitable for my situation i also find most of the java script code for that they worked but only with the vertical scroll not with the horizontal scroll and also combination of header and rows doesn't match.
Finally i have found a solution with javascript here is the link bellow :-
scrollable horizontal and vertical grid view with fixed headers
Refer Here which is 100% working
https://stackoverflow.com/a/59357398/11863405
Static Header for Gridview Control
You can try overflow css property.
// create this Js and add reference
var GridViewScrollOptions = /** #class */ (function () {
function GridViewScrollOptions() {
}
return GridViewScrollOptions;
}());
var GridViewScroll = /** #class */ (function ()
{
function GridViewScroll(options) {
this._initialized = false;
if (options.elementID == null)
options.elementID = "";
if (options.width == null)
options.width = "700";
if (options.height == null)
options.height = "350";
if (options.freezeColumnCssClass == null)
options.freezeColumnCssClass = "";
if (options.freezeFooterCssClass == null)
options.freezeFooterCssClass = "";
if (options.freezeHeaderRowCount == null)
options.freezeHeaderRowCount = 1;
if (options.freezeColumnCount == null)
options.freezeColumnCount = 1;
this.initializeOptions(options);
}
GridViewScroll.prototype.initializeOptions = function (options) {
this.GridID = options.elementID;
this.GridWidth = options.width;
this.GridHeight = options.height;
this.FreezeColumn = options.freezeColumn;
this.FreezeFooter = options.freezeFooter;
this.FreezeColumnCssClass = options.freezeColumnCssClass;
this.FreezeFooterCssClass = options.freezeFooterCssClass;
this.FreezeHeaderRowCount = options.freezeHeaderRowCount;
this.FreezeColumnCount = options.freezeColumnCount;
};
GridViewScroll.prototype.enhance = function ()
{
this.FreezeCellWidths = [];
this.IsVerticalScrollbarEnabled = false;
this.IsHorizontalScrollbarEnabled = false;
if (this.GridID == null || this.GridID == "")
{
return;
}
this.ContentGrid = document.getElementById(this.GridID);
if (this.ContentGrid == null) {
return;
}
if (this.ContentGrid.rows.length < 2) {
return;
}
if (this._initialized) {
this.undo();
}
this._initialized = true;
this.Parent = this.ContentGrid.parentNode;
this.ContentGrid.style.display = "none";
if (typeof this.GridWidth == 'string' && this.GridWidth.indexOf("%") > -1) {
var percentage = parseInt(this.GridWidth);
this.Width = this.Parent.offsetWidth * percentage / 100;
}
else {
this.Width = parseInt(this.GridWidth);
}
if (typeof this.GridHeight == 'string' && this.GridHeight.indexOf("%") > -1) {
var percentage = parseInt(this.GridHeight);
this.Height = this.Parent.offsetHeight * percentage / 100;
}
else {
this.Height = parseInt(this.GridHeight);
}
this.ContentGrid.style.display = "";
this.ContentGridHeaderRows = this.getGridHeaderRows();
this.ContentGridItemRow = this.ContentGrid.rows.item(this.FreezeHeaderRowCount);
var footerIndex = this.ContentGrid.rows.length - 1;
this.ContentGridFooterRow = this.ContentGrid.rows.item(footerIndex);
this.Content = document.createElement('div');
this.Content.id = this.GridID + "_Content";
this.Content.style.position = "relative";
this.Content = this.Parent.insertBefore(this.Content, this.ContentGrid);
this.ContentFixed = document.createElement('div');
this.ContentFixed.id = this.GridID + "_Content_Fixed";
this.ContentFixed.style.overflow = "auto";
this.ContentFixed = this.Content.appendChild(this.ContentFixed);
this.ContentGrid = this.ContentFixed.appendChild(this.ContentGrid);
this.ContentFixed.style.width = String(this.Width) + "px";
if (this.ContentGrid.offsetWidth > this.Width) {
this.IsHorizontalScrollbarEnabled = true;
}
if (this.ContentGrid.offsetHeight > this.Height) {
this.IsVerticalScrollbarEnabled = true;
}
this.Header = document.createElement('div');
this.Header.id = this.GridID + "_Header";
this.Header.style.backgroundColor = "#F0F0F0";
this.Header.style.position = "relative";
this.HeaderFixed = document.createElement('div');
this.HeaderFixed.id = this.GridID + "_Header_Fixed";
this.HeaderFixed.style.overflow = "hidden";
this.Header = this.Parent.insertBefore(this.Header, this.Content);
this.HeaderFixed = this.Header.appendChild(this.HeaderFixed);
this.ScrollbarWidth = this.getScrollbarWidth();
this.prepareHeader();
this.calculateHeader();
this.Header.style.width = String(this.Width) + "px";
if (this.IsVerticalScrollbarEnabled) {
this.HeaderFixed.style.width = String(this.Width - this.ScrollbarWidth) + "px";
if (this.IsHorizontalScrollbarEnabled) {
this.ContentFixed.style.width = this.HeaderFixed.style.width;
if (this.isRTL()) {
this.ContentFixed.style.paddingLeft = String(this.ScrollbarWidth) + "px";
}
else {
this.ContentFixed.style.paddingRight = String(this.ScrollbarWidth) + "px";
}
}
this.ContentFixed.style.height = String(this.Height - this.Header.offsetHeight) + "px";
}
else {
this.HeaderFixed.style.width = this.Header.style.width;
this.ContentFixed.style.width = this.Header.style.width;
}
if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {
this.appendFreezeHeader();
this.appendFreezeContent();
}
if (this.FreezeFooter && this.IsVerticalScrollbarEnabled) {
this.appendFreezeFooter();
if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {
this.appendFreezeFooterColumn();
}
}
var self = this;
this.ContentFixed.onscroll = function (event) {
self.HeaderFixed.scrollLeft = self.ContentFixed.scrollLeft;
if (self.ContentFreeze != null)
self.ContentFreeze.scrollTop = self.ContentFixed.scrollTop;
if (self.FooterFreeze != null)
self.FooterFreeze.scrollLeft = self.ContentFixed.scrollLeft;
};
};
GridViewScroll.prototype.getGridHeaderRows = function () {
var gridHeaderRows = new Array();
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
gridHeaderRows.push(this.ContentGrid.rows.item(i));
}
return gridHeaderRows;
};
GridViewScroll.prototype.prepareHeader = function () {
this.HeaderGrid = this.ContentGrid.cloneNode(false);
this.HeaderGrid.id = this.GridID + "_Header_Fixed_Grid";
this.HeaderGrid = this.HeaderFixed.appendChild(this.HeaderGrid);
this.prepareHeaderGridRows();
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
this.appendHelperElement(this.ContentGridItemRow.cells.item(i));
this.appendHelperElement(this.HeaderGridHeaderCells[i]);
}
};
GridViewScroll.prototype.prepareHeaderGridRows = function () {
this.HeaderGridHeaderRows = new Array();
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
var gridHeaderRow = this.ContentGridHeaderRows[i];
var headerGridHeaderRow = gridHeaderRow.cloneNode(true);
this.HeaderGridHeaderRows.push(headerGridHeaderRow);
this.HeaderGrid.appendChild(headerGridHeaderRow);
}
this.prepareHeaderGridCells();
};
GridViewScroll.prototype.prepareHeaderGridCells = function () {
this.HeaderGridHeaderCells = new Array();
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
for (var rowIndex in this.HeaderGridHeaderRows) {
var cgridHeaderRow = this.HeaderGridHeaderRows[rowIndex];
var fixedCellIndex = 0;
for (var cellIndex = 0; cellIndex < cgridHeaderRow.cells.length; cellIndex++) {
var cgridHeaderCell = cgridHeaderRow.cells.item(cellIndex);
if (cgridHeaderCell.colSpan == 1 && i == fixedCellIndex) {
this.HeaderGridHeaderCells.push(cgridHeaderCell);
}
else {
fixedCellIndex += cgridHeaderCell.colSpan - 1;
}
fixedCellIndex++;
}
}
}
};
GridViewScroll.prototype.calculateHeader = function () {
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
var gridItemCell = this.ContentGridItemRow.cells.item(i);
var helperElement = gridItemCell.firstChild;
var helperWidth = parseInt(String(helperElement.offsetWidth));
this.FreezeCellWidths.push(helperWidth);
helperElement.style.width = helperWidth + "px";
helperElement = this.HeaderGridHeaderCells[i].firstChild;
helperElement.style.width = helperWidth + "px";
}
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
this.ContentGridHeaderRows[i].style.display = "none";
}
};
GridViewScroll.prototype.appendFreezeHeader = function () {
this.HeaderFreeze = document.createElement('div');
this.HeaderFreeze.id = this.GridID + "_Header_Freeze";
this.HeaderFreeze.style.position = "absolute";
this.HeaderFreeze.style.overflow = "hidden";
this.HeaderFreeze.style.top = "0px";
this.HeaderFreeze.style.left = "0px";
this.HeaderFreeze.style.width = "";
this.HeaderFreezeGrid = this.HeaderGrid.cloneNode(false);
this.HeaderFreezeGrid.id = this.GridID + "_Header_Freeze_Grid";
this.HeaderFreezeGrid = this.HeaderFreeze.appendChild(this.HeaderFreezeGrid);
this.HeaderFreezeGridHeaderRows = new Array();
for (var i = 0; i < this.HeaderGridHeaderRows.length; i++) {
var headerFreezeGridHeaderRow = this.HeaderGridHeaderRows[i].cloneNode(false);
this.HeaderFreezeGridHeaderRows.push(headerFreezeGridHeaderRow);
var columnIndex = 0;
var columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
var freezeColumn = this.HeaderGridHeaderRows[i].cells.item(columnIndex).cloneNode(true);
headerFreezeGridHeaderRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
this.HeaderFreezeGrid.appendChild(headerFreezeGridHeaderRow);
}
this.HeaderFreeze = this.Header.appendChild(this.HeaderFreeze);
};
GridViewScroll.prototype.appendFreezeContent = function () {
this.ContentFreeze = document.createElement('div');
this.ContentFreeze.id = this.GridID + "_Content_Freeze";
this.ContentFreeze.style.position = "absolute";
this.ContentFreeze.style.overflow = "hidden";
this.ContentFreeze.style.top = "0px";
this.ContentFreeze.style.left = "0px";
this.ContentFreeze.style.width = "";
this.ContentFreezeGrid = this.HeaderGrid.cloneNode(false);
this.ContentFreezeGrid.id = this.GridID + "_Content_Freeze_Grid";
this.ContentFreezeGrid = this.ContentFreeze.appendChild(this.ContentFreezeGrid);
var freezeCellHeights = [];
var paddingTop = this.getPaddingTop(this.ContentGridItemRow.cells.item(0));
var paddingBottom = this.getPaddingBottom(this.ContentGridItemRow.cells.item(0));
for (var i = 0; i < this.ContentGrid.rows.length; i++) {
var gridItemRow = this.ContentGrid.rows.item(i);
var gridItemCell = gridItemRow.cells.item(0);
var helperElement = void 0;
if (gridItemCell.firstChild.className == "gridViewScrollHelper") {
helperElement = gridItemCell.firstChild;
}
else {
helperElement = this.appendHelperElement(gridItemCell);
}
var helperHeight = parseInt(String(gridItemCell.offsetHeight - paddingTop - paddingBottom));
freezeCellHeights.push(helperHeight);
var cgridItemRow = gridItemRow.cloneNode(false);
var cgridItemCell = gridItemCell.cloneNode(true);
if (this.FreezeColumnCssClass != null || this.FreezeColumnCssClass != "")
cgridItemRow.className = this.FreezeColumnCssClass;
var columnIndex = 0;
var columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
var freezeColumn = gridItemRow.cells.item(columnIndex).cloneNode(true);
cgridItemRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
this.ContentFreezeGrid.appendChild(cgridItemRow);
}
for (var i = 0; i < this.ContentGrid.rows.length; i++) {
var gridItemRow = this.ContentGrid.rows.item(i);
var gridItemCell = gridItemRow.cells.item(0);
var cgridItemRow = this.ContentFreezeGrid.rows.item(i);
var cgridItemCell = cgridItemRow.cells.item(0);
var helperElement = gridItemCell.firstChild;
helperElement.style.height = String(freezeCellHeights[i]) + "px";
helperElement = cgridItemCell.firstChild;
helperElement.style.height = String(freezeCellHeights[i]) + "px";
}
if (this.IsVerticalScrollbarEnabled) {
this.ContentFreeze.style.height = String(this.Height - this.Header.offsetHeight - this.ScrollbarWidth) + "px";
}
else {
this.ContentFreeze.style.height = String(this.ContentFixed.offsetHeight - this.ScrollbarWidth) + "px";
}
this.ContentFreeze = this.Content.appendChild(this.ContentFreeze);
};
GridViewScroll.prototype.appendFreezeFooter = function () {
this.FooterFreeze = document.createElement('div');
this.FooterFreeze.id = this.GridID + "_Footer_Freeze";
this.FooterFreeze.style.position = "absolute";
this.FooterFreeze.style.overflow = "hidden";
this.FooterFreeze.style.left = "0px";
this.FooterFreeze.style.width = String(this.ContentFixed.offsetWidth - this.ScrollbarWidth) + "px";
this.FooterFreezeGrid = this.HeaderGrid.cloneNode(false);
this.FooterFreezeGrid.id = this.GridID + "_Footer_Freeze_Grid";
this.FooterFreezeGrid = this.FooterFreeze.appendChild(this.FooterFreezeGrid);
this.FooterFreezeGridHeaderRow = this.ContentGridFooterRow.cloneNode(true);
if (this.FreezeFooterCssClass != null || this.FreezeFooterCssClass != "")
this.FooterFreezeGridHeaderRow.className = this.FreezeFooterCssClass;
for (var i = 0; i < this.FooterFreezeGridHeaderRow.cells.length; i++) {
var cgridHeaderCell = this.FooterFreezeGridHeaderRow.cells.item(i);
var helperElement = this.appendHelperElement(cgridHeaderCell);
helperElement.style.width = String(this.FreezeCellWidths[i]) + "px";
}
this.FooterFreezeGridHeaderRow = this.FooterFreezeGrid.appendChild(this.FooterFreezeGridHeaderRow);
this.FooterFreeze = this.Content.appendChild(this.FooterFreeze);
var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
if (this.IsHorizontalScrollbarEnabled) {
footerFreezeTop -= this.ScrollbarWidth;
}
this.FooterFreeze.style.top = String(footerFreezeTop) + "px";
};
GridViewScroll.prototype.appendFreezeFooterColumn = function () {
this.FooterFreezeColumn = document.createElement('div');
this.FooterFreezeColumn.id = this.GridID + "_Footer_FreezeColumn";
this.FooterFreezeColumn.style.position = "absolute";
this.FooterFreezeColumn.style.overflow = "hidden";
this.FooterFreezeColumn.style.left = "0px";
this.FooterFreezeColumn.style.width = "";
this.FooterFreezeColumnGrid = this.HeaderGrid.cloneNode(false);
this.FooterFreezeColumnGrid.id = this.GridID + "_Footer_FreezeColumn_Grid";
this.FooterFreezeColumnGrid = this.FooterFreezeColumn.appendChild(this.FooterFreezeColumnGrid);
this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeGridHeaderRow.cloneNode(false);
this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeColumnGrid.appendChild(this.FooterFreezeColumnGridHeaderRow);
if (this.FreezeFooterCssClass != null)
this.FooterFreezeColumnGridHeaderRow.className = this.FreezeFooterCssClass;
var columnIndex = 0;
var columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
var freezeColumn = this.FooterFreezeGridHeaderRow.cells.item(columnIndex).cloneNode(true);
this.FooterFreezeColumnGridHeaderRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
if (this.IsHorizontalScrollbarEnabled) {
footerFreezeTop -= this.ScrollbarWidth;
}
this.FooterFreezeColumn.style.top = String(footerFreezeTop) + "px";
this.FooterFreezeColumn = this.Content.appendChild(this.FooterFreezeColumn);
};
GridViewScroll.prototype.appendHelperElement = function (gridItemCell) {
var helperElement = document.createElement('div');
helperElement.className = "gridViewScrollHelper";
while (gridItemCell.hasChildNodes()) {
helperElement.appendChild(gridItemCell.firstChild);
}
return gridItemCell.appendChild(helperElement);
};
GridViewScroll.prototype.getScrollbarWidth = function () {
var innerElement = document.createElement('p');
innerElement.style.width = "100%";
innerElement.style.height = "200px";
var outerElement = document.createElement('div');
outerElement.style.position = "absolute";
outerElement.style.top = "0px";
outerElement.style.left = "0px";
outerElement.style.visibility = "hidden";
outerElement.style.width = "200px";
outerElement.style.height = "150px";
outerElement.style.overflow = "hidden";
outerElement.appendChild(innerElement);
document.body.appendChild(outerElement);
var innerElementWidth = innerElement.offsetWidth;
outerElement.style.overflow = 'scroll';
var outerElementWidth = innerElement.offsetWidth;
if (innerElementWidth === outerElementWidth)
outerElementWidth = outerElement.clientWidth;
document.body.removeChild(outerElement);
return innerElementWidth - outerElementWidth;
};
GridViewScroll.prototype.isRTL = function () {
var direction = "";
if (window.getComputedStyle) {
direction = window.getComputedStyle(this.ContentGrid, null).getPropertyValue('direction');
}
else {
direction = this.ContentGrid.currentStyle.direction;
}
return direction === "rtl";
};
GridViewScroll.prototype.getPaddingTop = function (element) {
var value = "";
if (window.getComputedStyle) {
value = window.getComputedStyle(element, null).getPropertyValue('padding-Top');
}
else {
value = element.currentStyle.paddingTop;
}
return parseInt(value);
};
GridViewScroll.prototype.getPaddingBottom = function (element) {
var value = "";
if (window.getComputedStyle) {
value = window.getComputedStyle(element, null).getPropertyValue('padding-Bottom');
}
else {
value = element.currentStyle.paddingBottom;
}
return parseInt(value);
};
GridViewScroll.prototype.undo = function () {
this.undoHelperElement();
for (var _i = 0, _a = this.ContentGridHeaderRows; _i < _a.length; _i++) {
var contentGridHeaderRow = _a[_i];
contentGridHeaderRow.style.display = "";
}
this.Parent.insertBefore(this.ContentGrid, this.Header);
this.Parent.removeChild(this.Header);
this.Parent.removeChild(this.Content);
this._initialized = false;
};
GridViewScroll.prototype.undoHelperElement = function () {
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
var gridItemCell = this.ContentGridItemRow.cells.item(i);
var helperElement = gridItemCell.firstChild;
while (helperElement.hasChildNodes()) {
gridItemCell.appendChild(helperElement.firstChild);
}
gridItemCell.removeChild(helperElement);
}
if (this.FreezeColumn) {
for (var i = 2; i < this.ContentGrid.rows.length; i++) {
var gridItemRow = this.ContentGrid.rows.item(i);
var gridItemCell = gridItemRow.cells.item(0);
var helperElement = gridItemCell.firstChild;
while (helperElement.hasChildNodes()) {
gridItemCell.appendChild(helperElement.firstChild);
}
gridItemCell.removeChild(helperElement);
}
}
};
return GridViewScroll;
}());
//add On Head
<head runat="server">
<title></title>
<script src="client/js/jquery-3.1.1.min.js"></script>
<script src="js/gridviewscroll.js"></script>
<script type="text/javascript">
window.onload = function () {
var gridViewScroll = new GridViewScroll({
elementID: "GridView1" // [Header is fix column will be Freeze ][1]Target Control
});
gridViewScroll.enhance();
}
</script>
</head>
//Add on Body
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
// <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<%-- <Columns>
<asp:BoundField DataField="SHIPMENT_ID" HeaderText="SHIPMENT_ID"
ReadOnly="True" SortExpression="SHIPMENT_ID" />
<asp:BoundField DataField="TypeValue" HeaderText="TypeValue"
SortExpression="TypeValue" />
<asp:BoundField DataField="CHAId" HeaderText="CHAId"
SortExpression="CHAId" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
</Columns>--%>
</asp:GridView>
<script type="text/javascript">
$(document).ready(function () {
var gridHeader = $('#<%=grdSiteWiseEmpAttendance.ClientID%>').clone(true); // Here Clone Copy of Gridview with style
$(gridHeader).find("tr:gt(0)").remove(); // Here remove all rows except first row (header row)
$('#<%=grdSiteWiseEmpAttendance.ClientID%> tr th').each(function (i) {
// Here Set Width of each th from gridview to new table(clone table) th
$("th:nth-child(" + (i + 1) + ")", gridHeader).css('width', ($(this).width()).toString() + "px");
});
$("#GHead1").append(gridHeader);
$('#GHead1').css('position', 'top');
$('#GHead1').css('top', $('#<%=grdSiteWiseEmpAttendance.ClientID%>').offset().top);
});
</script>
<div class="row">
<div class="col-lg-12" style="width: auto;">
<div id="GHead1"></div>
<div id="divGridViewScroll1" style="height: 600px; overflow: auto">
<div class="table-responsive">
<asp:GridView ID="grdSiteWiseEmpAttendance" CssClass="table table-small-font table-bordered table-striped" Font-Size="Smaller" EmptyDataRowStyle-ForeColor="#cc0000" HeaderStyle-Font-Size="8" HeaderStyle-Font-Names="Calibri" HeaderStyle-Font-Italic="true" runat="server" AutoGenerateColumns="false"
BackColor="#f0f5f5" OnRowDataBound="grdSiteWiseEmpAttendance_RowDataBound" HeaderStyle-ForeColor="#990000">
<Columns>
</Columns>
<HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top" />
<RowStyle Font-Names="Calibri" ForeColor="#000000" />
</asp:GridView>
</div>
</div>
</div>
</div>
Acheived by using java script...
Copy and paste given below javascript code inside the head tag.
<script language="javascript" type="text/javascript">
function MakeStaticHeader(gridId, height, width, headerHeight, isFooter) {
var tbl = document.getElementById(gridId);
if (tbl) {
var DivHR = document.getElementById('DivHeaderRow');
var DivMC = document.getElementById('DivMainContent');
var DivFR = document.getElementById('DivFooterRow');
//*** Set divheaderRow Properties ****
DivHR.style.height = headerHeight + 'px';
DivHR.style.width = (parseInt(width) - 16) + 'px';
DivHR.style.position = 'relative';
DivHR.style.top = '0px';
DivHR.style.zIndex = '10';
DivHR.style.verticalAlign = 'top';
//*** Set divMainContent Properties ****
DivMC.style.width = width + 'px';
DivMC.style.height = height + 'px';
DivMC.style.position = 'relative';
DivMC.style.top = -headerHeight + 'px';
DivMC.style.zIndex = '1';
//*** Set divFooterRow Properties ****
DivFR.style.width = (parseInt(width) - 16) + 'px';
DivFR.style.position = 'relative';
DivFR.style.top = -headerHeight + 'px';
DivFR.style.verticalAlign = 'top';
DivFR.style.paddingtop = '2px';
if (isFooter) {
var tblfr = tbl.cloneNode(true);
tblfr.removeChild(tblfr.getElementsByTagName('tbody')[0]);
var tblBody = document.createElement('tbody');
tblfr.style.width = '100%';
tblfr.cellSpacing = "0";
tblfr.border = "0px";
tblfr.rules = "none";
//*****In the case of Footer Row *******
tblBody.appendChild(tbl.rows[tbl.rows.length - 1]);
tblfr.appendChild(tblBody);
DivFR.appendChild(tblfr);
}
//****
DivHR.appendChild(tbl.cloneNode(true));
}
}
function OnScrollDiv(Scrollablediv) {
document.getElementById('DivHeaderRow').scrollLeft = Scrollablediv.scrollLeft;
document.getElementById('DivFooterRow').scrollLeft = Scrollablediv.scrollLeft;
}
</script>
Then Copy this code and paste and place your Grid View inside DivMainContent.
HTML Code:-
<div id="DivRoot" align="left">
<div style="overflow: hidden;" id="DivHeaderRow">
</div>
<div style="overflow:scroll;" onscroll="OnScrollDiv(this)" id="DivMainContent">
<%-- ***Place Your GridView Here***
<asp:GridView runat="server" ID="gridshow" Width="100%"
AutoGenerateColumns="False"ShowFooter="True">
<Columns>
//...................
</Columns>
</asp:GridView>
--%>
</div>
<div id="DivFooterRow" style="overflow:hidden">
</div>
</div>
Then Call function MakeStaticHeader in Aspx.CS File at the time of binding Gridview and pass the Some parameters.
ClientId of Gridview(Change GrdDisplay.ClientID as your gridview clientid).
Height of Scrollable div.
Width of Scrollable div.
Height of Table Header Row.
IsFooter (true/false) If you want to Make footer static or not.
-->After binding the Gridview, place below code
ScriptManager.RegisterStartupScript(Page, this.GetType(), "Key", "<script>MakeStaticHeader('" + GrdDisplay.ClientID + "', 400, 950 , 40 ,true); </script>", false);
Hope this will work for sure...

Scrolling with CSS

I have 4 tables that need to scroll, they are set up as follows:
Table1(static)
Table2(Horizontal Scrolling)
Table3(Vertical Scrolling)
Table4(Horizontal and Vertical Scrolling)
Table1 Table2
Table3 Table4
The tricky part of this is that Table 3 and 4 need to keep in sync as this is a listing of data broken out into two tables. Table 2 and 4 are in the same situation.
Any ideas?
No Javascript please as we have a script that works, but it is far too slow to work.
Thanks.
EDIT:
var tables = new Array();
var headerRowDivs = new Array();
var headerColumnDivs = new Array();
var bodyDivs = new Array();
var widths = new Array();
var heights = new Array();
var borderHorizontals = new Array();
var borderVerticals = new Array();
var tableWidths = new Array();
var tableHeights = new Array();
var arrayCount = 0;
var paddingTop = 0;
var paddingBottom = 0;
var paddingLeft = 0;
var paddingRight = 0;
function ScrollTableAbsoluteSize(table, width, height)
{
ScrollTable(table, null, null, width, height);
}
function ScrollTableRelativeSize(table, borderHorizontal, borderVertical)
{
ScrollTable(table, borderHorizontal, borderVertical, null, null);
}
function ScrollTable(table, borderHorizontal, borderVertical, width, height)
{
var childElement = 0;
if (table.childNodes[0].tagName == null)
{
childElement = 1;
}
var cornerDiv = table.childNodes[childElement].childNodes[0].childNodes[childElement].childNodes[childElement];
var headerRowDiv = table.childNodes[childElement].childNodes[0].childNodes[(childElement + 1) * 2 - 1].childNodes[childElement];
var headerColumnDiv = table.childNodes[childElement].childNodes[childElement + 1].childNodes[childElement].childNodes[childElement];
var bodyDiv = table.childNodes[childElement].childNodes[childElement + 1].childNodes[(childElement + 1) * 2 - 1].childNodes[childElement];
tables[arrayCount] = table;
headerRowDivs[arrayCount] = headerRowDiv;
headerColumnDivs[arrayCount] = headerColumnDiv;
bodyDivs[arrayCount] = bodyDiv;
borderHorizontals[arrayCount] = borderHorizontal;
borderVerticals[arrayCount] = borderVertical;
tableWidths[arrayCount] = width;
tableHeights[arrayCount] = height;
ResizeCells(table, cornerDiv, headerRowDiv, headerColumnDiv, bodyDiv);
widths[arrayCount] = bodyDiv.offsetWidth;
heights[arrayCount] = bodyDiv.offsetHeight;
arrayCount++;
ResizeScrollArea();
bodyDiv.onscroll = SyncScroll;
if (borderHorizontal != null)
{
window.onresize = ResizeScrollArea;
}
}
function ResizeScrollArea()
{
var isIE = true;
var scrollbarWidth = 17;
if (!document.all)
{
isIE = false;
scrollbarWidth = 19;
}
for (i = 0; i < arrayCount; i++)
{
bodyDivs[i].style.overflow = "scroll";
bodyDivs[i].style.overflowX = "scroll";
bodyDivs[i].style.overflowY = "scroll";
var diffWidth = 0;
var diffHeight = 0;
var scrollX = true;
var scrollY = true;
var columnWidth = headerColumnDivs[i].offsetWidth;
if (borderHorizontals[i] != null)
{
var width = document.documentElement.clientWidth - borderHorizontals[i] - columnWidth;
}
else
{
var width = tableWidths[i];
}
if (width > widths[i])
{
width = widths[i];
bodyDivs[i].style.overflowX = "hidden";
scrollX = false;
}
var columnHeight = headerRowDivs[i].offsetHeight;
if (borderVerticals[i] != null)
{
var height = document.documentElement.clientHeight - borderVerticals[i] - columnHeight;
}
else
{
var height = tableHeights[i];
}
if (height > heights[i])
{
height = heights[i];
bodyDivs[i].style.overflowY = "hidden";
scrollY = false;
}
headerRowDivs[i].style.width = width + "px";
headerRowDivs[i].style.overflow = "hidden";
headerColumnDivs[i].style.height = height + "px";
headerColumnDivs[i].style.overflow = "hidden";
bodyDivs[i].style.width = width + scrollbarWidth + "px";
bodyDivs[i].style.height = height + scrollbarWidth + "px";
if (!scrollX && isIE)
{
bodyDivs[i].style.overflowX = "hidden";
bodyDivs[i].style.height = bodyDivs[i].offsetHeight - scrollbarWidth + "px";
}
if (!scrollY && isIE)
{
bodyDivs[i].style.overflowY = "hidden";
bodyDivs[i].style.width = bodyDivs[i].offsetWidth - scrollbarWidth + "px";
}
if (!scrollX && !scrollY && !isIE)
{
bodyDivs[i].style.overflow = "hidden";
}
}
}
function ResizeCells(table, cornerDiv, headerRowDiv, headerColumnDiv, bodyDiv)
{
var childElement = 0;
if (table.childNodes[0].tagName == null)
{
childElement = 1;
}
SetWidth(
cornerDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes[childElement],
headerColumnDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes[0]);
SetHeight(
cornerDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes[childElement],
headerRowDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes[childElement]);
var headerRowColumns = headerRowDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes;
var bodyColumns = bodyDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes;
for (i = 0; i < headerRowColumns.length; i++)
{
if (headerRowColumns[i].tagName == "TD" || headerRowColumns[i].tagName == "TH")
{
SetWidth(
headerRowColumns[i],
bodyColumns[i],
i == headerRowColumns.length - 1);
}
}
var headerColumnRows = headerColumnDiv.childNodes[childElement].childNodes[childElement].childNodes;
var bodyRows = bodyDiv.childNodes[childElement].childNodes[childElement].childNodes;
for (i = 0; i < headerColumnRows.length; i++)
{
if (headerColumnRows[i].tagName == "TR")
{
SetHeight(
headerColumnRows[i].childNodes[0],
bodyRows[i].childNodes[childElement],
i == headerColumnRows.length - 1);
}
}
}
function SetWidth(element1, element2, isLastColumn)
{
// alert(element2 + "\n\n" + element2.offsetWidth);
var diff = paddingLeft + paddingRight;
if (element1.offsetWidth < element2.offsetWidth)
{
element1.childNodes[0].style.width = element2.offsetWidth - diff + "px";
element2.childNodes[0].style.width = element2.offsetWidth - diff + "px";
}
else
{
element2.childNodes[0].style.width = element1.offsetWidth - diff + "px";
element1.childNodes[0].style.width = element1.offsetWidth - diff + "px";
}
}
function SetHeight(element1, element2, isLastRow)
{
var diff = paddingTop + paddingBottom;
if (element1.offsetHeight < element2.offsetHeight)
{
element1.childNodes[0].style.height = element2.offsetHeight - diff + "px";
element2.childNodes[0].style.height = element2.offsetHeight - diff + "px";
}
else
{
element2.childNodes[0].style.height = element1.offsetHeight - diff + "px";
element1.childNodes[0].style.height = element1.offsetHeight - diff + "px";
}
}
function SyncScroll()
{
for (i = 0; i < arrayCount; i++)
{
headerRowDivs[i].scrollLeft = bodyDivs[i].scrollLeft;
headerColumnDivs[i].scrollTop = bodyDivs[i].scrollTop;
}
}
We got the code from this link.
I hope this helps.
As it stands, the code is far too bulky to process the amount of data we need to. We have approximately 5000 rows of data per month that needs to be displayed on the page.
If by "need to keep in sync" you mean that when you scroll one of them, the other scrolls too, you can't do this with CSS, because you can't manipulate scroll position using CSS.
And one more thing, have in mind that scrollbar in IE goes inside the element and overlaps 20px of this element (there is a workaround for this), and in all other browsers scrollbar goes outside the element.
You can use CSS to set the height of an element and then set overflow:auto (this will give you scroll bars when needed).
Its very hard to get rows of a table to scroll properly. I've been trying with things such as wrapping a table row in a div (or vice versa) and setting a max-height and overflow of that div.
That's the best I can do with out seeing what you are trying to do.
function ResizeCells(table, cornerDiv, headerRowDiv, headerColumnDiv, bodyDiv)
{
var childElement = 0;
if (table.childNodes[0].tagName == null)
{
childElement = 1;
}
SetWidth(
cornerDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes[childElement],
headerColumnDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes[0]);
SetHeight(
cornerDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes[childElement],
headerRowDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes[childElement]);
var headerRowColumns = headerRowDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes;
var bodyColumns = bodyDiv.childNodes[childElement].childNodes[childElement].childNodes[0].childNodes;
for (i = 0; i < headerRowColumns.length; i++)
{
if (headerRowColumns[i].tagName == "TD" || headerRowColumns[i].tagName == "TH")
{
SetWidth(
headerRowColumns[i],
bodyColumns[i],
i == headerRowColumns.length - 1);
}
}
var headerColumnRows = headerColumnDiv.childNodes[childElement].childNodes[childElement].childNodes;
var bodyRows = bodyDiv.childNodes[childElement].childNodes[childElement].childNodes;
for (i = 0; i < headerColumnRows.length; i++)
{
if (headerColumnRows[i].tagName == "TR")
{
SetHeight(
headerColumnRows[i].childNodes[0],
bodyRows[i].childNodes[childElement],
i == headerColumnRows.length - 1);
}
}
}
function SetWidth(element1, element2, isLastColumn)
{
// alert(element2 + "\n\n" + element2.offsetWidth);
var diff = paddingLeft + paddingRight;
if (element1.offsetWidth < element2.offsetWidth)
{
element1.childNodes[0].style.width = element2.offsetWidth - diff + "px";
element2.childNodes[0].style.width = element2.offsetWidth - diff + "px";
}
else
{
element2.childNodes[0].style.width = element1.offsetWidth - diff + "px";
element1.childNodes[0].style.width = element1.offsetWidth - diff + "px";
}
}
function SetHeight(element1, element2, isLastRow)
{
var diff = paddingTop + paddingBottom;
if (element1.offsetHeight < element2.offsetHeight)
{
element1.childNodes[0].style.height = element2.offsetHeight - diff + "px";
element2.childNodes[0].style.height = element2.offsetHeight - diff + "px";
}
else
{
element2.childNodes[0].style.height = element1.offsetHeight - diff + "px";
element1.childNodes[0].style.height = element1.offsetHeight - diff + "px";
}
}
function SyncScroll()
{
for (i = 0; i < arrayCount; i++)
{
headerRowDivs[i].scrollLeft = bodyDivs[i].scrollLeft;
headerColumnDivs[i].scrollTop = bodyDivs[i].scrollTop;
}
}
I appoligize, this part will not format no matter what I do, sorry about the poor formatting.

Resources