Webforms - Expand Dynamically created TreeNodes on Title Click - javascript

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.

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.

Javascript method call from code behind

I visited Calling java script from codebehind and other questions marked as duplicate by some users. But specific to my problem none of them are helpful.
I have an already built CMS and I need to change one of the module which was built using a user control. I cannot hereby add runat="server"attribute to the form and head tags.
I am having a
<asp:GridView ID="gdvResxKeyValue" runat="server" Width="100%"AutoGenerateColumns="False">`</asp:GridView>`
and
<asp:TreeView ID="tvList" ShowLines="True" runat="server" ImageSet="Msdn" OnSelectedNodeChanged="tvList_SelectedNodeChanged">
<SelectedNodeStyle CssClass="sfSelectednode" />
</asp:TreeView>
gdvResxKeyValue is bind while selection of nodes is made in treeview ie.
protected void tvList_SelectedNodeChanged(object sender, EventArgs e)
{
gdvResxKeyValue.DataSource = lstResDef;
gdvResxKeyValue.DataBind();
this.Page.ClientScript.RegisterStartupScript(this.GetType(),LocalizationGlobalVariable5", string.Format("edition();"), true);
}
At last column of gdvResxKeyValue I have an image as
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="imgEditResxValue" CssClass="sfEdit" runat="server" ImageUrl="~/Administrator/Templates/Default/images/imgedit.png" />
</ItemTemplate>
</asp:TemplateField>
and I need a image click handler using javascript using minified version of jquery-1.9.1.js. so have written code as..
<script type="text/javascript">
//<![CDATA[
$.Localization = {
TextAreaID: 0,
FilePath: "",
ID: 0,
GridID: '<%=gdvResxKeyValue.ClientID%>'
};
function edition() {
$('#'+ $.Localization.GridID).on('click', 'img[class="sfEdit"]', function () {
var index = $(this).attr("alt");
$.Localization.ID = index;
var data = $('#' + $.Localization.GridID + ' textarea[title="' + index + '"]').val();
$('#txtResxValueEditor').val(data);
ShowPopUp("editorDiv");
});
}
</script>
But it is not working.
Try to put your grid to div wrapper:
<div id="myDiv">
....<asp:GridView ID="gdvResxKeyValue"....
</div>
and JavaScript:
$('#myDiv .sfEdit').click(function(){
alert('called');
});
EDIT: just noticed you call the startup script registration on every postback (the Change event of your treeview). It's not needed. Simply include your JavaScript file, something like:
$(document).ready(function(){
$('#myDiv .sfEdit').click(function(){
var imgId = $(this).attr('id');
alert('called ' + imgId);
});
});
and keep the gridview in div wrapper as described above.
Rather calling javascript method on clicking the image. On the ready of document I have written following code and finally got my problem solved.
$(document).on('click', "#" + $.Localization.GridID + ' img.sfEdit', function (e) {
var index = $(this).attr("alt");
$.Localization.ID = index;
var data = $('#' + $.Localization.GridID + ' textarea[title="' + index + '"]').val();
$('#txtResxValueEditor').val(data);
ShowPopUp("editorDiv");
e.preventDefault();
});

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.

asp dropdownlist populated from xml list how to do add tooltips

PLEASE HELP WHAT AM I DOING WRONG?
I have an xml list of countries in the format of
<COUNTRY value="blah" title="blah">blah blah</COUNTRY>
I have a asp dropdownlist thats populated from the extensive xml list and dropdownlist html format is:
<asp:DropDownList ID="mCOUNTRY" runat="server" Width="205" onmouseover="showHideTooltip()"> </asp:DropDownList>
-----showHideTooltip() below-----
<script language="JavaScript">
function showHideTooltip()
{
var obj = document.getElementById("mCOUNTRY");
obj.title[obj.selectedIndex].title;
}
</SCRIPT>
</CODE>
On mouse over event show tooltip dropdownlist items by using C# example
Use tooltip in Asp.net dropdownlist items by mouse over event with Example using C#:
http://asp-net-by-parijat.blogspot.in/2014/08/show-tooltip-dropdownlist-items-by.html
You might like to look at this post on show/hide tooltips with jQuery, you could adapt from this SO answer, or this SO answer
I think you would need to do something like this:
<div id="tooltip" style="display:none;">Content will go here</div>
<asp:DropDownList ID="mCOUNTRY" runat="server" Width="205"
onmouseover="showTooltip()" onmouseout="hide()"> </asp:DropDownList>
with this for the javascript
<script language="JavaScript">
function showTooltip() {
var obj = document.getElementById("mCOUNTRY");
var title = obj.title[obj.selectedIndex].title;
var tooltip = document.getElementById("tooltip");
tooltip.innerHtml = title;
tooltip.style.visibility = 'visible';
tooltip.style.left = event.screenX + 'px';
tooltip.style.top = event.screenY + 'px';
}
function hideTooltip(){
document.getElementById("tooltip").style.visibility = 'hidden';
}
</script>
A jQuery solution (as mentioned above would be more elegant though)

Categories