How to make the Default focus in content page from master page - c#

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();

Related

Creating and finding dynamic controls on a page

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.

How to make textbox visible when previous textbox contains text

I have a WebForm in which i need to place around 30 textboxes mainly to enter barcode scanned data. I am making only the first textbox visible and i want the next textbox to be visible only when the previous textbox is filled with some text. I tried using 'If' condition as well in the textbox on selected change but it doesn't work. Any solutions?
You should use java-script for this because if you will use server side function for this then It will go to server so many times by this your application performance also will decrease.
So create a java-script function that will accept one argument. This argument will take next text box id (text box u want to display).
call this javascript function like this:- onkeyup="calgrid(this,"TextBox2");"
pass nexttextbox id in place of TextBox2...
<script type="text/javascript" language="javascript">
function calgrid(firsttextbox,nexttextbox)
{
var id=firsttextbox.id;
var lastindex= id.lastIndexOf("_");
var strclnt=id.slice(0,lastindex+1);
var txtboxvalue=document.getElementById(firsttextbox).value;
if(txtboxvalue!="")
{
document.getElementById(strclnt+nexttextbox).style.visibility='visible';
}
else
{
document.getElementById(strclnt+nexttextbox).style.display = "none";
}
}
</script>
note:- If you will do visible=false from textbox property then we cannt do visible=true from javascript. So Set style for all textbox style="display:none"
You can resolve your problem by Jquery.
I have make a sample code where i have take four Textbox. Initially only first text box is visible in Web form, when user enter some values in first TextBox next Textbox is automatically display if Previous textbox have a value if not next textbox is not visible.
Sample code is given below :
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
$('input:text:not(:eq(0))').hide()
$('input').on("change paste keyup", function () {
if ($(this).val().length > 0) {
$(this).next().show();
}
else
{
$(this).next().hide();
}
});
I have made sample application for same ,please click on given link for Demo
See Demo application
It's at Client side code so its performance is so fast rather than Server Side.
Please vote me if you feel your problem is resolved by my idea.
I'd name these text boxes similarly like "textbox1", "textbox2", "textbox3" so you can easily find the index of current text box. Then you can use KeyDown event to control what will be shown and what not. This is not a working example but it should give you a good direction.
int currentIndex = 1;
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
TextBox t = Controls["TextBox" + (currentIndex + 1).ToString()] as TextBox;
t.Visible = true;
currentIndex +=1;
}
Use can use Keydown event in your first textbox
try this code
initially set flag=1 as first textbox is going to be by default visible
private void visibleTextBox(Control c)
{
int flag = 1;
foreach (Control c1 in c.Controls)
{
if (c1.GetType() == typeof(TextBox))
{
if (flag == 1)
{
((TextBox)c1).Visible = true;
}
else
{
((TextBox)c1).Visible = false;
}
if (((TextBox)c1).Text != "")
{
flag = 1;
}
else
{
flag = 0;
}
}
}
}
Comparatively simple solution in JavaScript. The code should be somehow like this.
Define onchange event on text boxes like this:
<asp:TextBox ID="txt1" runat="server" onchange="show('txt1', 'txt2');"></asp:TextBox>
<asp:TextBox ID="txt2" runat="server" onchange="show('txt2', 'txt3');" Style="visibility: hidden;"></asp:TextBox>
Then use this JavaScript code to show the next TextBox conditionally. Put this code in the head tag of the page:
<script type="text/javascript">
function show(txtCurrent, txtNext) {
var valueCurrent = document.getElementById(txtCurrent).value;
//alert(valueCurrent);
if (valueCurrent.length > 0) {
document.getElementById(txtNext).style.visibility = 'visible';
}
else {
document.getElementById(txtNext).style.visibility = 'hidden';
}
}
</script>

How to check block adding characters if the input text is a special character?

I have a gridview and it has some columns .
For example: Name|Age|Birthday
How can I filter the textbox so if the user is typing a special character it won't be added.
I know I need to use this : ^[^0-9a-zA-Z]*$ , but I don't know how.
Thanks
OnBlur and OnKeyUp Events of TextBox
JavaScript
<script language="javascript" type="text/javascript">
function validation() {
var txt = document.getElementById('<%= txt.ClientID%>').value;
var regex = new RegExp('[^0-9a-zA-Z]+');
while (txt.match(regex)) {
if (txt.match(regex)[0] == "") break;
txt = txt.replace(regex, '');
}
document.getElementById('<%= txt.ClientID%>').value = txt;
}
function onkeyUpEvent() {
validation();
}
function onBlurEvent() {
validation();
}
</script>
MarkUp
<asp:TextBox ID="txt" runat="server" onkeyup="onkeyUpEvent();"
onblur="onBlurEvent();"></asp:TextBox>
var lastValidValue;
input.addEventListener('keydown', function(evt) {
// before change capture current value;
lastValidValue = input.value;
}, false);
function onchange(evt) {
if (/^[^0-9a-zA-Z]*$/.test(input.value))
// if its valid, update preserved field.
lastValidValue = input.value;
else
// otherwise revert to previous data.
input.value = lastValidValue;
}
input.addEventLisenter('keyup', onchange, false);
input.addEventListener('change', onchange, false);
where input is a reference to your textbox.

Get Textbox Value from Masterpage using c#

I have a search textbox situated on a masterpage like so:
<asp:TextBox ID="frmSearch" runat="server" CssClass="searchbox"></asp:TextBox>
<asp:LinkButton ID="searchGo" PostBackUrl="search.aspx" runat="server">GO</asp:LinkButton>
The code behind for the search page has the following to pick up the textbox value (snippet):
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
Page previousPage = PreviousPage;
TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("frmSearch");
searchValue.Text = tbSearch.Text;
//more code here...
}
All works great. BUT not if you enter a value whilst actually on search.aspx, which obviously isn't a previous page. How can I get round this dead end I've put myself in?
If you use the #MasterType in the page directive, then you will have a strongly-typed master page, meaning you can access exposed properties, controls, et cetera, without the need the do lookups:
<%# MasterType VirtualPath="MasterSourceType.master" %>
searchValue.Text = PreviousPage.Master.frmSearch.Text;
EDIT: In order to help stretch your imagination a little, consider an extremely simple property exposed by the master page:
public string SearchQuery
{
get { return frmSearch.Text; }
set { frmSearch.Text = value; }
}
Then, through no stroke of ingenuity whatsoever, it can be seen that we can access it like so:
searchValue.Text = PreviousPage.Master.SearchQuery;
Or,
PreviousPage.Master.SearchQuery = "a query";
Here is a solution (but I guess its old now):
{
if (PreviousPage == null)
{
TextBox tbSearch = (TextBox)Master.FindControl("txtSearch");
searchValue.Value = tbSearch.Text;
}
else
{
TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("txtSearch");
searchValue.Value = tbSearch.Text;
}
}

selecting a node of treeview after postback - asp.net

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.

Categories