Show Row Index in Gridview - javascript

I have been looking throughout Stack Overflow and can't seem to find anything related to my issue.
I have a gridview that displays results and I have some buttons on each row to move that row up or down.
After I click the button, I would like it to change the row index, so say row 1 goes to row 2, then I would like the new row 2 to display 2 instead of 1.
So the row index isnt updated and stays its original row index.
I would like it so that the row index updates after the html button click is pressed. I will show the current code for moving up and down rows.
Preferably, I would like to integrate it into the javascript code I have already done, but if other code works I will use that.
This is my first post, so please go easy on me and ask any questions below and I will answer as fast as possible.
Thanks.

Will drag & drop work below is teh code for same
this process of GridView row reordering i.e. Drag and Drop ordering of GridView Rows using jQuery in ASP.Net.
The drag and drop ordering of GridView Rows will be performed using jQuery UI Sortable Plugin.
<asp:GridView ID="gvLocations" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Id" ItemStyle-Width="30">
<ItemTemplate>
<%# Eval("Id") %>
<input type="hidden" name="LocationId" value='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Location" HeaderText="Location" ItemStyle-Width="150" />
<asp:BoundField DataField="Preference" HeaderText="Preference" ItemStyle-Width="100" />
</Columns>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string query = "SELECT Id, Location, Preference FROM HolidayLocations ORDER BY Preference";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvLocations.DataSource = dt;
gvLocations.DataBind();
}
}
}
}
}
JS part
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=gvLocations]").sortable({
items: 'tr:not(tr:first-child)',
cursor: 'pointer',
axis: 'y',
dropOnEmpty: false,
start: function (e, ui) {
ui.item.addClass("selected");
},
stop: function (e, ui) {
ui.item.removeClass("selected");
},
receive: function (e, ui) {
$(this).find("tbody").append(ui.item);
}
});
});
</script>
**Code to save same in in DB**
protected void UpdatePreference(object sender, EventArgs e)
{
int[] locationIds = (from p in Request.Form["LocationId"].Split(',')
select int.Parse(p)).ToArray();
int preference = 1;
foreach (int locationId in locationIds)
{
this.UpdatePreference(locationId, preference);
preference += 1;
}
Response.Redirect(Request.Url.AbsoluteUri);
}
private void UpdatePreference(int locationId, int preference)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE HolidayLocations SET Preference = #Preference WHERE Id = #Id"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Id", locationId);
cmd.Parameters.AddWithValue("#Preference", preference);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Complete Article here

Wouldn't something like this work?
$('table').change(function(){
let allrows = $('tr', this);
for(let i = 0; i < allrows.length; i++){
$('td.index', $(allrows[i])).val(i+1);
}
});
i just wrote this up, and didnt debug/test it so you might find a bug, but this should point you in the right direction

Related

How do i close child window in asp.net c#?

I am now creating a web site with webforms in C#. I made a button that opens the child window with a landscape photo if pressed. On top of the landscape painting in the child window, comments written in the parent window are displayed.
The user can press this button to open as many child windows as they press, separate from the ASPX page with this button. Just press the button 10 times to open 10 pages of child windows with pictures of landscape paintings.
What I want to do is not press the button 10 times to create 10 child windows, but I want to update the child window 9 times after the child window is created in the first time.
If possible, I'd like you to tell me how to do it. Also, I thought that it would be difficult for me to do so, so I thought that if I pressed the button after the second time, the old child window created by pressing the button before that would close and a new child window would be born.
Below is the code I wrote.
↓aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
↓aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string url=string.Format("WebForm1.aspx?q={0:s}",TextBox1.Text);
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "OpenNewWindow", "window.open('" + url + "', null);",true);
}
The problem is twofold. One way is to update the child window. The other way is to close the child window. I thought that the line window would be closed with the code below, so I tried it lightly, but the parent window closed and the child window remained.
↓aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
string url=string.Format("WebForm1.aspx?q={0:s}",TextBox1.Text);
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "CloseNewWindow", "window.Close('" + url + "', null);",true);
}
What should I do?
I think you best consider having this pop up appear on the CURRENT page.
And now that you want to restrict to "one", then that makes this a WHOLE lot less work.
There are more "dialog" systems then flavors of ice cream to choose from.
but, the two most common are the bootstrap ones, and the one from jQuery.UI.
I find the jQuery.UI VERY easy to work with - and you can control position with much greater ease then bootstrap ones.
And given that you have a SUPER high chance of already having jQuery, then adopting jQuery.UI from the same folks makes all the more sense.
And jQuery.UI dialogs can be "modal", and that means focus can't get out of the dialog until you "ok" or "save" or whatever.
So, lets take a simple GridView. Say we have some rows, and a "image".
When we click on the edit button, we pop a dialog with the picture, and also allow you to edit the comments.
So, our Grid is say this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:ImageButton ID="cmdView" runat="server" Width="150px"
ImageUrl = '<%# Eval("ImagePath") %>'
OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code on page load is thus this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Fighters");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
And now we have this:
So, the way jQuery.UI works?
You create a simple "div" on the same page, and it will become your "dialog"
You then hide with style=display:none.
So our markup for this "div" to disaplay the picture "big" and edit comments is this
(we drop it below the GV)
So, we have this simple markup to display picture, and let user edit comments for the picture:
<div id="EditOne" runat="server" style="text-align:center;display:none" clientidmode="static">
<br />
<asp:Image ID="Image1" runat="server" width="90%" />
<br />
<h4>Edit Description</h4>
<asp:TextBox ID="txtDescription" runat="server"
TextMode="MultiLine" Columns="90" Height="100px">
</asp:TextBox>
<br />
</div>
<asp:Button ID="cmdSave" runat="server" Text="Save" ClientIDMode="Static"
style="display:none" OnClick="cmdSave_Click"/>
Note careful in above - right below the div, I have a hidden save button.
So, now the jQuery routine that we pop to display this div as a dialog:
this:
<script>
function popimage(btn) {
pWidth = "50%"
myDialog = $("#EditOne");
myDialog.dialog({
title: "Edit Comments",
modal: true,
width: pWidth,
closeText: "",
show: "fade",
buttons: {
Save: function () {
myDialog.dialog("close")
$('#cmdSave').click()
},
Cancel: function () {
myDialog.dialog("close")
}
}
})
}
</script>
So, now we only need our button row click from the grid (I used image button).
That code is this:
We get the current row PK id, pull from database, and fill out the "div", and then pop it:
protected void cmdView_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM Fighters WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PK;
DataTable rstFighter = MyRstP(cmdSQL);
Image1.ImageUrl = rstFighter.Rows[0]["ImagePath"].ToString();
txtDescription.Text = rstFighter.Rows[0]["Description"].ToString();
ViewState["rstFighter"] = rstFighter;
Page.ClientScript.RegisterStartupScript(
this.GetType(),"MyEdit","popimage()", true);
}
And now our save button, to send information back to database is this:
protected void cmdSave_Click(object sender, EventArgs e)
{
// Save comments (and other fields back to database)
DataTable rstFigher = (DataTable)ViewState["rstFighter"];
rstFigher.Rows[0]["Description"] = txtDescription.Text;
SaveData(rstFigher, "Fighters");
LoadGrid(); // refresh grid to show any edits
}
So, the results now look like this when I click on a row image:
Note how the web page behind goes "darker gray" and the pop up is model.
So, I would consider jQuery.UI dialogs.
And I did use two helper routines (after all, we don't write the same code over and over to get get a simple data table, right???).
Those two helper routines were:
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
void SaveData(DataTable rstData,string sTable)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM " + sTable, conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
}
}
}
So, as above shows you have complete control over closing the pop up dialogue, but MUCH more important we can then also with ease update the current page to reflect those changes ( in our example update the description text in our pick list GridView). And with both the grid display and editing on the same page we also require much less code.

how to pass selected row of gridview in popup window into parent page

I have 2 pages in asp.net with c# .
a parent.aspx and popup.aspx.
I passed a querystring(id) into page load of popup.aspx and used function to call row of table base on id and show gridview on popup.aspx.
now I want to select this row, and pass details into text boxes of parent.aspx that is open now.
Everything is ok and row of table is passed into text boxes, but it is into new window popup of parent.aspx page, that I don't want this.
I want pass details into this page(parent.aspx) that now is open.
How can I do that.thanks.
below is my code for pass id to pop-up window
protected void btn_search_id_Click(object sender, ImageClickEventArgs e)
{
string str1 = Encrypt(txt_sh_p.Text);
btn_search_id.Attributes.Add("onclick", "window.open('popup.aspx?sh_p_=" + str1 + "','Report','width=750,height=500,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,left=200,top=50'); return false;");
}
my code for reading id and select row and display row in gridview on page load event of popup.aspx:
protected void Page_Load(object sender, EventArgs e)
{
DAL.Sab_Ashkh sabt_ashkh = new DAL.Sab_Ashkh();
List<DAL.Sab_Ashkh> sabt_ashkh_list;
sabt_ashkh.sh_p = Decrypt(Request.QueryString["sh_p_"]);
sabt_ashkh_list = sabt_ashkhDB.GetShakh_find(sabt_ashkh.sh_p);
grid_ashkh.Visible = true;
grid_ashkh.DataSource = grid_ashkh_list;
grid_ashkh.DataBind();
}
and html code for pass row to parent page:
<Columns>
<asp:HyperLinkField DataTextField="id_shakh" DataNavigateUrlFields="id_shakh" DataNavigateUrlFormatString="parent.aspx?id_shakh={0}"
HeaderText="id" ItemStyle-Width = "150" />
<asp:TemplateField HeaderText="select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width = "150px" DataField = "sh_p" HeaderText ="kod"
>
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
</Columns>
I am just telling you how you can change the variable in Main page in popup page like:
Suppose Parent.aspx have:
<script type="text/javascript">
var items =[];
</script>
and in popup.aspx you can do something like :
window.opener.items.push(yourSelectedRows);
but as another workaround you can also use local storage like:
localStorage.setItem("selectedRecords", JSON.stringify(selectedRows));
suppose selectedRows are your array of object or anything else but as my experience the selectedRecords would be accessible in all HTML pages.
hope this help you.
Hi Aria Thanks for reply. I pass id by query string into popup window and show gridview . and this script for popup win :
<script type="text/javascript">
function SetName() {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("txt_id_mah");
grid = document.getElementById("grid_ashkh");
var cellPivot;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length; i++) {
cellPivot = grid.rows[i].cells[1];
TXT.value = cellPivot;
}
}
}
window.close();
}
</script>
but does not work.

How to call javascript from code behind for Repeater control

There is a span element that need to load data dynamically from a Repeater control.
The problem that I encounter is only first span element can display the value. The subsequent will display blank.
I've simplify the code behind as below.
private int incre = 0;
protected void Page_Load(object sender, EventArgs e)
{
foreach (RepeaterItem ritem in FeaturedRepeater.Items)
{
HtmlGenericControl span = ritem.FindControl("countdown") as HtmlGenericControl;
span.Load += new EventHandler(test);
}
}
protected void test(object sender, EventArgs e)
{
HtmlGenericControl span = (HtmlGenericControl)sender;
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "timer(" + incre + ")", true);
incre++;
}
Javascript function in .aspx file example as below:
function timer(increment, timespan) {
var id = 'ContentPlaceHolder1_FeaturedRepeater_countdown_' + increment;
document.getElementById(id).innerHTML = id;
}
HTML part:
<asp:Repeater runat="server" ID="FeaturedRepeater" OnItemDataBound="FeaturedRepeater_ItemDataBound">
<ItemTemplate>
<span id='countdown' runat="server"></span>
</ItemTemplate>
</asp:Repeater>
Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("CallMyFunction{0}", incre), "timer(" + incre + ");", true);
you can't register the same key more then one time.
that's why changing "CallMyFunction" to string.Format("CallMyFunction{0}", incre) will work
btw
and ; after every javascript function call.

Fix Header Row of ASP.NET GridView

Before getting in details, I would like to mention I've tried various solutions from stackoverflow and net too. But, none suitable in my scenario. So, I provided detailed information.
In an ASP.NET 2.0 Web Application, a gridview controls is used and columns of that gridview are generated at runtime with respect to user's settings.
So, in Default.aspx the gridview definition is as below:
<div id="DivListB" runat="server" onscroll="SaveScrollValue(); SetListFloatingHeader()" visible="True">
<asp:GridView ID="ObjList" runat="server" OnLoad="ReloadGrid" CssClass="ObjList" AutoGenerateColumns="false" OnRowDataBound="ObjList_RowDataBound" AutoGenerateSelectButton="false" OnSelectedIndexChanged="ObjList_SelectedIndexChanged" OnRowCreated="ObjList_RowCreated">
<Columns>
<asp:TemplateField HeaderText="&nbsp" ItemStyle-Width="46px" ItemStyle-HorizontalAlign="Center">
<HeaderTemplate>
<asp:CheckBox AutoPostBack="true" ID="chkAll" runat="server" OnCheckedChanged="HeaderChk_Changed" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox AutoPostBack="true" ID="chkRow" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "Selection")%>' OnCheckedChanged="ChkRow_OnCheckChange" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The gridview columns are added at runtime and below method creates the columns depending upon user settings from web.config:
private void CreateDefaultGridView(Hashtable htPartSchema)
{
string sTempHeader, sTempAlignment, sTempWidth, sTempVisible;
try
{
//get partlist settings section from web.config
NameValueCollection plConfigKeys = (NameValueCollection)ConfigurationManager.GetSection("CONFIG_SETTINGS/PL_SETTINGS");
//cond: check partlist config keys exist
if (plConfigKeys != null && plConfigKeys.Count > 0)
{
//loop: every key present in configruation
foreach (string key in plConfigKeys)
{
//cond: config key is present in part schema
if (htPartSchema.ContainsKey(key.ToUpper()) == true)
{
//create new databound column
BoundField gridCol = new BoundField();
//assign datafield to bind with data table column
gridCol.DataField = key;
//get value from config key
string sKeyValue = plConfigKeys[key].ToString();
try
{
string[] sTempArray = sKeyValue.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
sTempHeader = sTempArray[0];
sTempAlignment = sTempArray[1];
sTempWidth = sTempArray[2];
sTempVisible = sTempArray[3];
PLDefaultColumnHeaderAlignments.Add(sTempHeader, sTempAlignment);
PLDefaultColumHeaderWidths.Add(sTempHeader, sTempWidth);
}
catch
{
sTempHeader = string.Empty;
sTempAlignment = string.Empty;
sTempWidth = string.Empty;
sTempVisible = "false";
}
if (sTempVisible.ToLower().Equals("true"))
{
//assign display header text
gridCol.HeaderText = sTempHeader;
//add the column in the gridview
ObjList.Columns.Add(gridCol);
//cond: to check the specified alignment
if (sTempAlignment.ToUpper() == "L")
{
gridCol.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
gridCol.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
}
else if (sTempAlignment.ToUpper() == "R")
{
gridCol.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
gridCol.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
}
else if (sTempAlignment.ToUpper() == "C")
{
gridCol.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
gridCol.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
}
if (string.IsNullOrEmpty(sTempWidth) == false)
{
gridCol.ControlStyle.Width = Unit.Pixel(int.Parse(sTempWidth));
gridCol.HeaderStyle.Width = int.Parse(sTempWidth);
gridCol.HeaderStyle.Wrap = false;
gridCol.ItemStyle.Wrap = false;
gridCol.ItemStyle.Width = Unit.Pixel(int.Parse(sTempWidth));
//set column width
double dTempColWidth = 120; //default value
double.TryParse(sTempWidth, out dTempColWidth);
//change width of grid view according to column sizes
ObjList.Width = new Unit((ObjList.Width.Value + dTempColWidth), UnitType.Pixel);
}
}
gridCol.ItemStyle.Wrap = false;
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
And when rows are bounded with GridView few events and css are also applied at runtime in DataRowBound Event of GridView as mentioned below:
protected void ObjList_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
int iDataRowsCounter = 0;
if (e.Row.RowType == DataControlRowType.DataRow)
{
//get datatable from
DataTable dtList = (DataTable)Session["ListTable" + ViewState["ViewerId"]];
//get position of the respective row
string strPostion = dtList.Rows[e.Row.RowIndex]["Position"].ToString();
string strLinkNum = dtList.Rows[e.Row.RowIndex]["LinkNumber"].ToString();
//get row check box
CheckBox cbRow = ((CheckBox)e.Row.FindControl("chkRow"));
string pnum = dtList.Rows[e.Row.RowIndex]["PartNumber"].ToString();
if (a_PartNumber != null && pnum == a_PartNumber)
{
HighlightPic.Value = HighlightPic.Value + "||" + e.Row.RowIndex.ToString();
e.Row.Style.Add(HtmlTextWriterStyle.BackgroundColor, "#3D98FF");
e.Row.Style.Add(HtmlTextWriterStyle.Color, "#FFFFFF");
}
//mouse hover effects on gridview (CSS)
e.Row.Attributes.Add("onmouseover", "this.className='ObjListHighlight'");
e.Row.Attributes.Add("onmouseout", "this.className='ObjListNormal'");
//keep position of the row in case needed in javascript
e.Row.Attributes.Add("RowPosition", strPostion);
//on row checkbox check change of a single row
cbRow.Attributes.Add("onclick", "OnRowCheckChange(this, 'ObjList')");
//on full row click highlight picture
e.Row.Attributes.Add("onclick", "HighlightPicture('" + strPostion + "'," + e.Row.RowIndex + ", false)");
//on row double click
e.Row.Attributes.Add("ondblclick", "OnRowDblClick(" + e.Row.RowIndex + ",'ObjList')");
}
else if (e.Row.RowType == DataControlRowType.Header)
{
//find header checkbox control
CheckBox cbHeader = ((CheckBox)e.Row.FindControl("chkAll"));
e.Row.Attributes.Add("class", "item_HeaderRow");
e.Row.Cells[0].Attributes.Add("class", "item_HeaderCell");
//add header change event on checkbox click
cbHeader.Attributes.Add("onclick", "OnHeaderCheckChange(this,'ObjList')");
}
}
catch
{
throw new Exception(ex.Message);
}
}
Its presentation is something like below:
Respective css is as below:
.ObjList
{
height: auto;
}
.ObjListHighlight
{
background-color: #CAE4FF;
cursor: pointer;
}
.ObjListNormal
{
background-color: White;
cursor: pointer;
}
.ObjList tr.row
{
cursor: pointer;
color: #1B3A7A;
background-color: #FFFFFF;
}
.ObjList tr.row:hover
{
background-color: #CAE4FF;
}
.ObjList tr.row_selected
{
cursor: default;
color: #FFFFFF;
background-color: #3D98FF;
}
What I wanted to do is to fix the header row of that gridview. Solution can be in javascript or jQuery. Suggestions are appreciated.
Try this,
ASPX page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script src="gridviewScroll.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
gridviewScroll();
});
function gridviewScroll() {
gridView1 = $('#gridtest').gridviewScroll({
width: 600,
height: 300,
railcolor: "#F0F0F0",
barcolor: "#CDCDCD",
barhovercolor: "#606060",
bgcolor: "#F0F0F0",
freezesize: 1,
arrowsize: 30,
headerrowcount: 1,
railsize: 16,
barsize: 8
});
}
</script>
<div style="width: 100%; height: 400px; overflow: scroll">
<asp:GridView ID="gridtest" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="ID" SortExpression="UserID" ReadOnly="true" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
</Columns>
</asp:GridView>
</div>
CS page:
protected void Page_Load(object sender, EventArgs e)
{
gridtest.DataSource = getUserDetails();
gridtest.DataBind();
}
public class details
{
public int UserID { get; set; }
public string FirstName {get;set;}
}
public List<details> getUserDetails()
{
List<details> gt = new List<details>();
for (int i = 1; i < 40; i++)
{
details objDetails = new details();
objDetails.UserID = i;
objDetails.FirstName = "test" + i;
gt.Add(objDetails);
}
return gt;
}
For reference use this : http://gridviewscroll.aspcity.idv.tw/
Your best bet would be to create two GridViews. One purely for the header. Second, for the body wrapped in a scrollable div just below the first one. Position the second gridview with a negative top margin to hide its header. This way you will use the header of the first girdview and scroll the second one.
Alternatively, you can use a plugin like this one: http://www.fixedheadertable.com
This plugin also uses the same logic as I described above.

Avoid page reload on Button click having onClick and onClientClick events in ASP.NET

I have an Asp server control button for which I have onClick for processing code in code behind and onClientClick to process javascript code. The codes are:
Update: As per Icarus solution, updated codes :
Button source:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
style="z-index: 1; left: 648px; top: 202px; position: absolute"
Text="Show route" OnClientClick="droute(); return false" />
<asp:HiddenField ID="hdncroute" runat="server" />
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
using (con = new MySqlConnection("server=localhost; uid=root;password=as64ws;database=Gmaps"))
da = new MySqlDataAdapter("select * from routes where uid='" + Session["uname"].ToString() + "'", con);
da.Fill(ds, "mroute");
foreach (DataRow r in ds.Tables[0].Rows)
{
uroute.Add(r["latlng"].ToString());
}
croute = new string[uroute.Count];
croute = uroute.ToArray();
hdncroute.Value = string.Join("&", croute);
}
Javascript function:
function droute()
{
var route=[];
var temp;
temp = eval(document.getElementById('<%= hdncroute.ClientID %>').value);
route= temp.split('&');
//Polyline icon n line settings
var iconsetngs= {path:google.maps.SymbolPath.FORWARD_CLOSED_ARROW, fillColor:'#FF0000'};
var polylineoptns= {strokeColor:'#3333FF',strokeOpacity:0.8,strokeWeight:3,map:map,icons:[{icon:iconsetngs,offset:'100%'}]};
polyline= new google.maps.Polyline(polylineoptns);
//Loop to add locations and draw line
var path= polyline.getPath();
for(var i=0;i<route.length;i++)
{
var marker= new google.maps.Marker({position:route[i],map:map});
path.push(route[i]);
google.maps.event.addListener(marker,'click',showiwindow);
}
//Event Listener's
function showiwindow(event)
{
iwindow.setContent("<b>Coordinates are:</b><br/>Latitude:"+event.latLng.lat()+"<br/>Longitude:"+event.latLng.lng());
iwindow.open(map,this);
}
}
I know that writing return false for javascript function will avoid refresh, and also onClick has void return type. But still my page reloads on button click.
You have an error here:
route = document.getElementById('<%= croute %>').value;
It should be:
route = document.getElementById('<%= croute.ClientID %>').value;
Update:
Markup - declare a hidden element in the page
<asp:hiddenfield id="hdnCroute" runat="server" />
//code behind
int [] croute = ...
hdnCroute.Value = "["+string.Join(",",croute)+"]";
Now Javascipt:
//now you have an array back in javascript
var route= eval(document.getElementById('<%= hdnCroute.ClientID %>').value);
why the page reload?
OnClientClick="droute(); return false"
at inner of browser like this:
button.onclick = function(){
droute();
return false
};
while droute is going wrong,so,return false doesn't work.

Categories