I am using a treeview control. I am buliding the tree dynamically. sometimes the tree becomes larger and the down scroll bar is need to see the entire tree.
user can select a node from the tree. if one node is selected ,i change the color of the node from server side.
my problem is that if a user selected a node which is bottom in the tree(means, the user used the down scrollbar to see that node), after postback it shows the top of the tree.to see the selected node the user need to use the down scroll bar.
I need to show the selected node after postback. How can I do this?
I am using c# and asp.net
With help of jquery we can send the selected node id to the query string and on document.ready we can read back and highlight that node.
Have a look on the code:
Code behind onclick code:
public void TreeView1_OnClick(Object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(
Page,
Page.GetType(),
"HighlightSelectedNode",
"HighlightSelectedNode();",
true
);
}
and the javascript:
<script type="text/javascript" language="javascript">
function HighlightSelectedNode() {
var selectedNodeID = $('#<%= TreeView1.ClientID %>_SelectedNode').val();
if (selectedNodeID != "") {
document.location.href = "http://" + window.location.host
+ window.location.pathname
+ "?Node=" + selectedNodeID;
return false;
} else {
// alert("Not found");
}
}
// Highlight active node on pageload.
$(document).ready(function () {
var querystring = location.search.replace('?', '').split('&');
var queryObj = {};
for (var i = 0; i < querystring.length; i++) {
var name = querystring[i].split('=')[0];
var value = querystring[i].split('=')[1];
queryObj[name] = value;
}
var nodeID = queryObj["Node"];
$('#' + nodeID).css({ 'background-color': '#888'});
});
</script>
You can use update panel to work around this issue.
Related
There is a problem to find a dynamic control on a page. The dynamic control is created every time when a user press a button. The button calls the following JavaScript function and create a new components.
<script type="text/javascript">
var uploadCount = 1;
function addFileInput(fName) {
var only_file_name = fName.replace(/^.*[\\\/]/, '');
var $div = $('<div />', {runat: 'server'});
var $cbox = $('<input />', { type: 'checkbox', id: 'attachement' + uploadCount, value: fName, checked: "true", runat: 'server'}).addClass;
var $label = $('<label />', { 'for': 'attachement' + uploadCount, text: only_file_name });
$div.append($cbox);
$div.append($label);
$('#newAttachment').append($div);
$("#uploadCountValue").prop("value", uploadCount);
uploadCount++;
}
</script>
newAttachment is DIV section on the page.
<div id="newAttachement" runat="server" />
The DIV section is situated inside section. The problem is when a user presses the button on the form I can't find the dynamic created components. The following code shows how I try to find the components:
for (int i = 1; i <= Convert.ToInt32(uploadCountValue.Value); i++)
{
if (RecursiveFind(newAttachement, "attachement" + i) != null)
{
... to do something
}
}
public Control RecursiveFind(Control ParentCntl, string NameToSearch)
{
if (ParentCntl.ID == NameToSearch)
return ParentCntl;
foreach (Control ChildCntl in ParentCntl.Controls)
{
Control ResultCntl = RecursiveFind(ChildCntl, NameToSearch);
if (ResultCntl != null)
return ResultCntl;
}
return null;
}
I have detected that Controls count value is always zero in spite of there are dynamic components there.
I would be happy to get any help from us. Thanks.
to find the controls created in the client-end you can't search them in the Page.Controls collection instead try to look for them in the Request.Form[] array
you are creating the dynamic controls in javascript? i.e. you are creating html elements in javascript. It won't matter even if you put a runat="server" attribute in there, because it is still at the client-end. That would not be a part of the viewstate bag, so not populated in the controls collection.
you need to change your logic. create dynamic control in code-behind on button postback.
I currently use a hidden input field that is assigned the value of the tab that has just been selected, via javascript, like so:
function onTabSelecting(sender, args) {
var tab = args.get_tab(); //get selected tab
document.getElementById("MainContent_hdnPreviousTab").value = tab.get_text(); //assign value to hidden field
if (tab.get_pageViewID()) { //ignore
tab.set_postBack(false);
}
}
I then use this assigned value when the page is returned to, on client-side (ajax) PageLoad() event:
<script type="text/javascript" language="javascript">
var runOnce = false;
function pageLoad() {
if (!runOnce) {
var lastTab = document.getElementById("<%= hdnPreviousTab.ClientID %>");
if (lastTab.value) {
if (tabStrip) {
var tab = tabStrip.findTabByText(lastTab.value);
if (tab) {
tab.click();
}
}
}
runOnce = true;
}
}
</script>
Currently in IE this works fine (I know right?), the value that was previously set in javascript is still there and i am able to lcoate the tab that the user left the page on. However in FF, Chrome, etc. i have no such luck. The hidden field is returned to it's empty state (value = "") regardless of utilising viewstate or not.
Very curious as to whether anyone has an alternative method that would be appropriate in this situation. Please let me know if this is unclear.
Many thanks.
You could use localstorage.
localStorage.setItem('tab', value);
I have an update panel which is causing a postback on part of the page and after postback the control that had focus (which is not in the update panel) loses focus. How can I identify which control had focus and save that value, so that I can refocus to it when the page reloads. Thank you.
First I bind the focus on all input and keep the last focused control ID. Then after the UpdatePanel finish the load, I set the focus to the last one
// keep here the last focused id
var LastFocusedID = null;
function watchTheFocus()
{
// on every input that get the focus, I grab the id and save it to global var
$(":input").focus(function () {
LastFocusedID = this.id;
});
}
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
}
// after the updatePanel ends I re-bind the focus, and set the focus
// to the last one control
function EndRequest(sender, args) {
if(LastFocusedID != null)
$('#' + LastFocusedID).focus();
watchTheFocus();
}
jQuery(document).ready(function()
{
watchTheFocus();
});
The only think is that I use jQuery to make it, but I present here my idea, you can make it with little more code with out jQuery.
You can get what element has focus with javascript using the activeElement and hasFocusproperty to HTMLDocument object.It might not be supported by all since it's HTML5.
You can solve like this
var last_focused = null;
$(function () {
//store last focused element.
$("input").live("focus", function(){
last_focused = $(this);
});
});
//in Script manager
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
function pageLoaded(sender, args)
{
if(last_focused != null)
{
last_focused.focus();
}
}
I have a list in my aspx page where the values for the list are coming from the database. The data can be added to the list successfully
But how can I retrieve the value of the selected list item when I click on that? (ul_Click event)
I don't want to redirect to another page because I'm using AJAX. so i want it in the same page. that's why i commented the
<ul runat="server" id="ulList" onclick="ul_Click">
</ul>
The data is binded to the list in the page_load event.
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection("Server=NIPUNA-PC\\SQLEXPRESS; Database=XXX; Trusted_Connection=True");
string[] itemList = authorList();
foreach (string item in itemList)
{
HtmlGenericControl newLi = new HtmlGenericControl("li");
//newLi.InnerHtml = "" + item + "";
newLi.InnerText = item;
ulList.Controls.Add(newLi);
}
}
I want the ul_Click() event?
seems like you were on track with the innerHtml thing. You can pass some kind of an ID with the link.
"" + item + "";
then do a request querystring and check for that id. if it's there, then call a function?
i'm not 100% sure, but what you're trying to do might be impossible otehrwise with HtmlGenericControl. I don't think you can bind an onclick event to HtmlGenericControl
Your other option is perhaps go with ajax/javascript
EDIT> just saw the comment. so .... you might do something like
"" + item + "";
you could also do
"" + item + "";
i personally dislike the last one as <a href="#" version because it can cause bad client side behavior such as to go to page top or something stupid like that when clicked.
just to wrap things up. Keep in mind that you'll need a client side javascript to handle the function
<script language="javascript">
function callMyAjaxFunction(bookid){
// do something
}
</script>
adding to robert's ideal instead of including item twice in the markup, you might do
" + item + "
<script language="javascript">
function callMyAjaxFunction(e){
alert(e.innerHTML);// do something
}
</script>
I have masterpage with content place holder. i have contentpage which is using master page . in all my content page i need to default focus on the text box so that the user can directly type in text box instead moving the mouse over the textbox. in some page there is no text box so that i donnot nnet keep default focus over there
Is there any way i can do it in my master page once and can reuse that in all my content page
thank you
try using this...
((TextBox)Master.FindControl("txtRequiredFocus")).Focus();
You could include this in your master page's load event:
// if the ID is constant you can use this:
/*TextBox textBox = (TextBox)Page.Controls[0]
.FindControl("ContentPlaceHolder1")
.FindControl("myTextBox");
*/
// this will look for the 1st textbox without hardcoding the ID
TextBox textBox = (TextBox)Page.Controls[0]
.FindControl("ContentPlaceHolder1")
.Controls.OfType<TextBox>()
.FirstOrDefault();
if (textBox != null)
{
textBox.Focus();
}
This would match up with a content page that has the following markup:
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:TextBox ID="myTextBox" runat="server" />
</asp:Content>
EDIT: if LINQ isn't an option then you can use this instead:
foreach (Control control in Page.Controls[0].FindControl("ContentPlaceHolder1").Controls)
{
if (control is TextBox)
{
((TextBox)control).Focus();
break;
}
}
Indiscriminate JavaScript approach to selecting the first valid input field on a page:
function SelectFirstInput() {
var bFound = false;
for (f = 0; f < document.forms.length; f++) {
// for each element in each form
for (i = 0; i < document.forms[f].length; i++) {
// if it's not a hidden element
if (document.forms[f][i].type != "hidden") {
// and it's not disabled
if (document.forms[f][i].disabled != true) {
// set the focus to it
document.forms[f][i].focus();
var bFound = true;
}
}
// if found in this element, stop looking
if (bFound == true)
break;
}
// if found in this form, stop looking
if (bFound == true)
break;
}
}
<script language="javascript" type="text/javascript" >
window.onload=function(){
var t= document.getElementById('<%=TextBox1.clientID %>');
t.focus();
}
</script>
If you use jQuery, a possible solution is:
Give the textbox you want to set focus to a special class. "focus" works well for this purpose.
Write code such as the following in your master page or included by your master page in a js script file:
$(document).ready
(
function()
{
//get an array of DOM elements matching the input.focus selector
var focusElements = $("input.focus").get();
//if a focus element exists
if(focusElements.length > 0)
{
focusElements[0].focus();
}
}
);
A similar approach using vanilla JavaScript would be to tag the textbox with a special attribute. Let's use focus.
window.onload = function()
{
//get all input elements
var inputElements = document.getElementsByTagName("input");
var elementToFocus = null;
for(var i = 0; i < inputElements.length; ++i)
{
var focusAttribute = inputElements[i].getAttribute("focus");
if(focusAttribute)
{
elementToFocus = inputElements[i];
break;
}
}
if(elementToFocus)
{
elementToFocus.focus();
}
};
Control masterC =
Page.Master.FindControl("ContentPlaceHolder1");
TextBox TextBox1 =
masterC.FindControl("TextBoxUsername") as TextBox;
TextBox1.Focus();