Set focus on an asp.net control on Page Load - javascript

I want to set focus on a control when page is loaded.
I wrote this code but not working..
protected void setFocus(System.Web.UI.Control ctrl)
{
string s = "<SCRIPT language='javascript'>document.getElementById('" + ctrl.ID + "').focus() </SCRIPT>";
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "focus", s);
}
and this line in PageLoad method:
this.setFocus(txtHeightfeet);
Please help.
EDIT:
This is HTML:
<input name="ctl00$MainContent$txtHeightfeet" type="text" maxlength="2" id="MainContent_txtHeightfeet" class="textEntry2" style="width:65px;" />
This is aspx code:
<asp:TextBox ID="txtHeightfeet" runat="server" CssClass="textEntry2" MaxLength="2" Width="65"></asp:TextBox> ft
and in code behind cs file, i declared it the same as you have mentioned.

You should be able to just call the Focus() method of the control.
No need for that Javascript.
protected void Page_Load(object sender, EventArgs e)
{
txtHeightfeet.Focus();
}

Related

How can i do database CRUD operations by taking parameters from aspx.cs file?

<script type="text/javascript">
function GetValue3(id) {
text1 = documnet.getElementById(input parameter from cs file);
alert("this is from cs file");
//database transactions here <-------method1
}
$(function () {
button1 = document.getElementById(input parameter from aspx file);
$("[id*=Button1]").on("click", function () {
alert("this is from aspx file");
//database transactions here <-------method2
})
})
</script>
My question is that there are two procedures for database transactions, first from taking parameters from aspx.cs code befind file and second from aspx file.
In my code i want to do database transactions using second approach (by using parameters from aspx.cs code behind) because it is required in my coding.
please guide me how can i build this approach.
not sure what you are trying to achieve but you need to differentiate between client events and server events
to get element in JS you can get its ID from 'ClientID'
ASPX file:
<asp:TextBox ID="txtTest" OnTextChanged="txtTest_TextChanged" runat="server" AutoPostBack="true" ></asp:TextBox>
<asp:Button ID="btn1" OnClick="btn1_Click" runat="server" Text="Click" />
<script type="text/javascript">
function textFromTextBox() {
var text1 = documnet.getElementById('<%= this.txtTest.ClientID %>');
}
</script>
aspx cs file
protected void btn1_Click(object sender, EventArgs e)
{
var text = txtTest.Text;
}
protected void txtTest_TextChanged(object sender, EventArgs e)
{
var updatedText = txtTest.Text;
}
EDIT:
you cannot attach code behind method to ordinary html element. You can only attach javascript events to these elements or inputs. If its the case then its irrelevant if you are using asp.net web forms, python, ruby on backend server.
<input type="button" id="sbutton" value="Save" />
<script type="text/javascript">
(function (){
documnet.getElementById('sbutton').addEventListener("click", function(){ //do your crud operation });;
})
()
</script>

Calling onclickserver in html it doesn't fire any event

I'm facing a problem. When calling an html input tag on C# it doesn't fire any event. Can you please give an advice on the below html code and c# code?
<input type="submit" id="btnBeforeOk" runat="server" name="btnBeforeOk" value="Login" onserverclick="BtnBeforeOk_ServerClick" />
protected void BtnBeforeOk_ServerClick(object sender, EventArgs e)
{
Label1.Text = "Youhana";
}
}
Have you tried with your button code like this:
<script language="C#" runat="server">
protected void BtnBeforeOk_ServerClick(object sender, EventArgs e) {
....
}
</script>

Get value from html input text type textbox as string and pass it to C# hashtable being used in aspx

The textbox is defined as html input text type and takes input from the users. This value is needed to pass as key to hashtable defined in aspx.cs file being used in aspx file. But the correct value is not being given and an exception is being thrown. Any help in this regard would be helpful. Thanks
The code is as follows:
<% =Hashtable[document.getElementbyId("Textbox").Value]%>
document.getElementbyId("Textbox").Value is not giving the correct output. If it is replaced by a string value acting as key then it works fine. The only problem is getting the string value from textbox.
First include jquery in head section
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
Try below code to read textbox value :
First read text box value using
var key = $("[id$=Textbox]").val();
and see if value is present in texbox if present use this to read hash value
<% =Hashtable[key]%>
Try this it worked for me :
aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function GetHashtable() {
alert("<% = hashtable[this.test] %>");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtKey" OnTextChanged="txtKey_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
</div>
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</body>
</html>
Code behind :
public partial class _Default : System.Web.UI.Page
{
protected int test;
public Hashtable hashtable = new Hashtable();
static Hashtable sHashtable = new Hashtable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
sHashtable[1] = "One";
sHashtable[2] = "Two";
sHashtable[13] = "Thirteen";
}
}
protected void txtKey_TextChanged(object sender, EventArgs e)
{
test = Convert.ToInt32("0" + txtKey.Text);
hashtable = sHashtable;
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetHashtable", "GetHashtable();", true);
}
}

ScriptManager.RegisterStartupScript() method not working - ASP.NET, C#

I have used ScriptManager.RegisterStartupScript() method in order to show an alert when particular thing happens in back end.It works fine in page load method but not in particular method which is called when a specific button is clicked . I Couldn't find a solution because in another page it works fine in both page load and the method.
Script Manager RegisterStartupScript Method
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
HTML
<asp:HiddenField runat="server" ClientIDMode="Static" ID="PostBackController"/>
<button class="some-class" id="btnSave" runat="server" onclick="btnSave_clientClick();">SAVE</button>
Javascript
function btnSave_clientClick() {
// code
if (some_condition) {
$('#PostBackController').val("btn_save");
__doPostBack();
}
}
Page Load Method
protected void Page_Load(object sender, EventArgs e)
{
if (PostBackController.Value == "btn_save")
{
uploadDocSave_ServerClick();
}
}
Method Wish should be called when button Clicked
protected void uploadDocSave_ServerClick()
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
}
My deepest condolences for OP if you still have to work with Webforms. This is how you can solve it in a minimal way while reducing traffic:
Codebehind sample:
public partial class About : Page, IPostBackEventHandler
{
protected void Page_Init(object sender, EventArgs e)
{
// Unless the button is serverside clicking it will reload the page
// registering the page like this prevents a page reload.
var scriptManager = ScriptManager.GetCurrent(Page);
scriptManager?.RegisterAsyncPostBackControl(Page);
}
/// <inheritdoc />
public void RaisePostBackEvent(string eventArgument)
{
var javascriptCode = $"alert('server method called and triggered client again. {DateTime.Now.ToString("s")}');";
// if your key isn't changed this script will only execute once
ScriptManager.RegisterStartupScript(udpMain, typeof(UpdatePanel), Guid.NewGuid().ToString(), javascriptCode, true);
// updating the updatepanel will inject your script without reloading anything else
udpMain.Update();
}
}
Webforms sample:
<script type="text/javascript">
function clientFunction(sender, args) {
alert('client function called');
<%= Page.ClientScript.GetPostBackEventReference(Page, "callServerFunction") %>
args.preventDefault();
}
</script>
<asp:UpdatePanel runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional" ID="udpMain">
<ContentTemplate>
<h2><%: Title %>.</h2>
<h3>Your application description page.</h3>
<p>Use this area to provide additional information.</p>
<button onclick="clientFunction(); return false;">raise server function</button>
</ContentTemplate>
</asp:UpdatePanel>
Try this:
If you Used Update Panels Then You can Use:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "javascriptFunction();", true);
Other Wise You can Use
ClientScript.RegisterStartupScript
(GetType(),Guid.NewGuid().ToString(), "javascriptFunction();",true);
Try this:
Client side:
Use Literal Control
<asp:Literal ID="IMsg" runat="server" Text=""/>
Server side:
string msg = "<script>alert('Change successfully');</script>";
IMsg.Text = msg;
I think it will help you. It works fine in my projects.
Try to remove line containing:
__doPostBack();
in the JavaScript code.
Sorry I am late at the party. Use this overload of RegisterStartupScript method, and set the first parameter the button on which you want to click to register the javascript function. Like:
ScriptManager.RegisterStartupScript(btnSave, this.GetType(), "alert", "alert('msg');", true);
Cheers!
THE REALLY SIMPLE WAY
You can wire up a <button runat="server"></button> to a server event using the onserverclick attribute:
HTML:
<button class="some-class" id="btnSave" onserverclick="uploadDocSave_ServerClick" runat="server">SAVE</button>
C# Handler:
protected void uploadDocSave_ServerClick(Object sender, EventArgs args)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
}
WITH CLIENT SIDE VALIDATION
If you want to add some sort of JavaScript check before postback, you can do that from the onclick attribute:
HTML:
<button class="some-class" id="btnSave" onclick="return btnSave_clientClick();" onserverclick="uploadDocSave_ServerClick" runat="server">SAVE</button>
JavaScript:
function btnSave_clientClick() {
// code
if (some_condition) {
return true; // allows the control to do a postback
}
}
C# Handler:
protected void uploadDocSave_ServerClick(Object sender, EventArgs args)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
}

Force asp.net page postback from server

I have a page that is created entirely dynamically in the code behind (oh joy).
On pressing a button on this page, more elements are added to the page - which is fine, however, the refreshed page doesn't appear until the next postback. I would do a redirect, but I want to keep the state of any data entered in the existing controls.
So - I need to force a postback from the server code behind code. I imagine that this involves inserting some js code - but beyond that, I've not had any joy at all.
Here is an example to make things clearer:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
A very simple page.
The code behind is simple too:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["data"] = 1;
}
PopulatePage();
}
private void PopulatePage()
{
int data = (int)Session["data"];
for (int n = 0; n < data; ++n)
{
TextBox tb = new TextBox();
tb.ID = n.ToString();
PlaceHolder1.Controls.Add(tb);
Literal lit = new Literal();
lit.Text = "<br/>";
PlaceHolder1.Controls.Add(lit);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int data = (int)Session["data"];
Session["data"] = ++data;
}
}
You click the button and more controls are added. This is way simpler than the page that I am having issues with, but it demonstrates the problems that I am having.
The postback is not needed and is a bit of a hack, you would be better off fixing the problem at the root.
private void PopulatePage()
{
for (int n = 0; n < Counter; n++)
{
CreateSingleControl(n);
}
}
private void CreateSingleControl(int index)
{
TextBox tb = new TextBox();
tb.ID = String.Format("text{0}", index);
PlaceHolder1.Controls.Add(tb);
Literal lit = new Literal();
lit.Text = "<br/>";
PlaceHolder1.Controls.Add(lit);
}
protected override void CreateChildControls()
{
PopulatePage();
base.CreateChildControls();
}
protected void Button1_Click(object sender, EventArgs e) {
CreateSingleControl(Counter);
Counter++;
}
private int Counter
{
get
{
return Counter = (int)(ViewState["data"] ?? 1);
}
set
{
ViewState["data"] = value;
}
}
Use the Request forms list to search unique control ID's
Something like this link below, last post, not sure his code is exactly correct, but you'll get the idea.
Searching for controls in Request.Form / Parsing a NameValueCollection
Give your controls unique IDs' and you can search for them on the postback.
Plus, i use to add other things to the ID to let the postback searching know what type of control it was, like adding txt_firstname, i know that firstname was a txtbox. Use regex to search the returned strings.

Categories