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=" " 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.
Related
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
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.
So, I've been searching the interwebs for days now and still haven't got any answers. So, here I am :). I've got a TreeView that I am populating with XML from a Sitemap (Web.sitemap) and is acting as a menu on a website. I want to be able to have the menu nodes toggle on clicking its title. That way, I can get rid of the +- checkboxes to make it look neater. So far, I can get them to toggle. But, only after I have pre-populated the node by first clicking the checkbox associated with it. Has anyone got any ideas how I can go about this?
This is my TreeView div
<div class="menu" style="width: auto; float:left; margin-top: 20px;">
<asp:SiteMapDataSource ID="smdsMenu" runat="server" SiteMapProvider="MainMenuSiteMapProvider"/>
<asp:TreeView ID="tvMenu" runat="server" DataSourceID="smdsMenu" ExpandDepth="1" ImageSet="Arrows" margin-top="0px">
<LeafNodeStyle BackColor="Transparent" CssClass="tvMenuL2" />
<HoverNodeStyle Font-Bold="True" BackColor="#1e8acb" ForeColor="Black" Font-Underline="False" />
<ParentNodeStyle BackColor="#6E7E94" CssClass="tvMenuL1" Font-Bold="false" />
<RootNodeStyle BackColor="#2c4566" CssClass="tvMenuL0" />
<SelectedNodeStyle Font-Underline="True" ForeColor="#1e8acb" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
</div>
This is my page loaded handler
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
tvMenu.Attributes.Add("onmousedown", "return OnTreeMouseClick(event)");
}
}
And this is my Javascript
<script lang="javascript" type="text/javascript">
function OnTreeMouseClick(evt) {
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var nodeClick = src.tagName.toLowerCase() == "span";
if (nodeClick) {
// Change tvMenu to ID of TreeView
var tvDataName = "tvMenu" + "_Data";
var tv = document.getElementById("tvMenu");
var tvData = window[tv.id + "_Data"];
var spanID = src.id;
var selectNode = document.getElementById(spanID);
var start = spanID.indexOf("tvMenu" + "t");
var length = 7; // length of TreeView ID + 1 for the letter t
var spanIndex = parseInt(spanID.substring(start + length));
if (spanIndex != NaN) {
var spanNode = "tvMenu" + "n" + spanIndex.toString();
var spanChildren = spanNode + "Nodes";
// Call toggle Node script
TreeView_ToggleNode(
tvData, // data
spanIndex, // index
document.getElementById(spanNode), // node
'', // lineType
document.getElementById(spanChildren) // children
);
}
}
return false;
}
</script>
I know that the node isn't being populated by my Javascript. But, I don't know how to use TreeView_PopulateNode without a datapath like the checkboxes do here.
<a id="tvMenun1" href="javascript:TreeView_PopulateNode(tvMenu_Data,1,document.getElementById('tvMenun1'),document.getElementById('tvMenut1'),null,' ','Overview','Home\\Overview','t','776cfb0b-fc9e-4ff1-8487-829a1162916d','tf')">
<img src="/WebResource.axd?d=8Ig4CKxOyXBIduEK8UJR2BXEYzKQWBLDFGfU4Y_g95G2TuDmM3zzGZE7CoW0qe4bVdRWK9Vp8x2MnX9eQ6Z66hsxeeTNg2xk5-CpNTJuS3Q1&t=636043022594211026" alt="Expand Overview" style="border-width:0;">
</a>
This is the generated HTML from my code
<span class="tvMenu_0 tvMenuL1 tvMenu_3" title="Overview" id="tvMenut1" style="border-style:none;font-size:1em;">Overview</span>
Any help with this would be GREATLY appreciated. Thanks.
I try to customize my asp:FileUpload control by using some css trick. When I finally upload the picture, it seems that the asp:FileUpload did not grab the file.
In the aspx page:
<style>
#file {
display:none;
}
</style>
<div>
<div style="float:left;">
<asp:Button ID="btnSelectPicture" runat="server" CssClass="btn2small" Text="Select Picture" OnClientClick="javascript:return false;" />
</div>
<asp:FileUpload ID="fuPicture" runat="server" />
<div id="inputUploadFileName" style="float:left; line-height: 2; margin: 0 15px;">No picture selected</div>
<div style="float:left;">
<asp:Button ID="btnUploadPicture" runat="server" Text="Upload" CssClass="btn2small" OnClick="btnUploadPicture_Click" ValidationGroup="vgUploadp"/>
</div>
<div id="errorFormatPicture" class="errorMessage" style="float:left; line-height:2; margin-left: 15px;"></div>
</div>
<script>
var wrapper = $('#<%=fuPicture.ClientID%>').css({ height: 0, width: 0, 'overflow': 'hidden' });
var fileInput = $('#<%=fuPicture.ClientID%>').wrap(wrapper);
fileInput.change(function () {
$this = $(this);
var fileName = $this.val();
fileName = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length);
if (fileName.length == 0)
fileName = "No picture selected";
else {
extension = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);
if (extension != "jpg" && extension != "png")
$("#errorFormatPicture").text(" * png or jpg only");
else {
$("#errorFormatPicture").text("");
$('#inputUploadFileName').text(fileName);
}
}
})
$('#<%=btnSelectPicture.ClientID%>').click(function () {
fileInput.click();
return false;
}).show();
</script>
Then in the aspx.cs page:
protected void btnUploadPicture_Click(object sender, EventArgs e)
{
Response.Write("has file? " + fuPicture.HasFile + "<BR>");
if (fuPicture.HasFile)
{
try
{
if (fuPicture.PostedFile.ContentType == "image/jpeg" || fuPicture.PostedFile.ContentType == "image/png")
{
if (fuPicture.PostedFile.ContentLength < 500000)
{
string fileDirectory = string.Format("/images/upload/ServiceRequest/{0}/temp_request/", UserId);
System.IO.Directory.CreateDirectory(fileDirectory);
string fileName = Path.GetFileName(fuPicture.FileName);
string _fullFile = fileDirectory + fileName;
fuPicture.SaveAs(_fullFile);
lbErrorUploadPicture.Text = "uploaded";
//Loadthumbnail();
}
else
lbErrorUploadPicture.Text = "Pictures must be less than 500 kb";
}
else
lbErrorUploadPicture.Text = "Pictures must be jpeg or png format";
}
catch (Exception ex)
{
lbErrorUploadPicture.Text = "Unexpected error: Pictures could not be uploaded. ";
}
}
}
The FileUpload never has a file in it. Where should I change it? Thank you all.
Nothing jumps out to me immediately. I'd suggest:
First, comment out your JavaScript. Does the FileUpload control work when you are not modifying the underlying HTML markup first? If so, take a closer look at these 2 lines in your JavaScript:
var wrapper = $('#<%=fuPicture.ClientID%>').css({ height: 0, width: 0, 'overflow': 'hidden' });
var fileInput = $('#<%=fuPicture.ClientID%>').wrap(wrapper);
Perhaps the culprit lies in trying to hide that value in the markup.
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.