how to put focus on a dynamically generated field in update panel - asp.net

i'm dynamically generating asp controls inside an update panel on a certain trigger. However, when the text control is generated, the focus goes on to the next pre-existing element and screws things up. Is there a way I can trigger a javascript event after the update panel has been updated?

The following worked when the control wasn't added though a async postback.
In the aspx/ascx control.
<asp:PlaceHolder runat="server" ID="placeHolder1"></asp:PlaceHolder>
In the codebehind.
TextBox test = new TextBox();
test.ID = "test";
test.TabIndex = 21;
test.Text = "test";
placeHolder1.Controls.Add(test);
string script = "document.getElementById('" + test.ClientID + "').focus();";
ScriptManager.RegisterStartupScript(this, typeof(TextBox), UniqueID, script, true);
It seems that the async postback sets the focus on the page. Pressing tab put the focus on the text Textbox.

Related

ASP.net - Gridview Textbox Enter Button Postback

I have a GridView with a Textbox and when the user changes the text within that box, I want them to be able to hit the enter button and postback and update the changes they made within that textbox on the row in the GridView.
I can't figure out how to do this?
Thanks,
Mark
You need to use some JavaScript code to do that - its on the page part. Here is one that I use (jQuery)
$(document).ready(function(){
// capture the editors
var AllEditors = jQuery('#<%= gvGridViewID.ClientID %> :input[type=text]');
AllEditors.keydown(function (e) {
if (e.keyCode == 13)
{
e.preventDefault();
// the [value=Update] is the default value to Update control of GridView
jQuery(this).parents("tr").find("input[value=Update]").click();
}
});
});
If you have it inside UpdatePanel, you need to initialize it each time the UpatePanel fires. If you have it inside a custom control, you need to add extra variables on the function names to avoid conflicts.

character encoding with asp.net dynamic textbox

Environment: .net 3.5, c#, sharepoint 2010
Existing functionality: I have a user control with a search text box and search button. When the submit button is hit, along with search results, a querystring with search keyword is built. On postback, the textbox is again populated with the search keyword from querystring. This works good.
Issue: Need to fix cross side scripting. so did a html.encode and again a filter to escape single quote with &amp#39; for the textbox value. but the textbox displays value as it is like "'searchingstring'".
I need to show the user only "Searchstring", but the value in the sourcecode should be &amp#39;searchingstring&amp#39; to prevent cross side script vulnerability.
(Note: Above text "&amp" is actually "&". not &amp#39. Since stackoverflow editor transforms it to single quotes, i replaced it with &amp for reading)
If i tried building the textbox dynamically on pageinit using stringbuilder, I am getting what i needed as i mentioned above.
eg:
StringBuilder sb = new StringBuilder();
if (Request.QueryString["str"] != null)
{
string strName = Request.QueryString["str"].ToString();
str_value = htmlCheckReturnData(strName ); //encoded string
sb.Append("<INPUT type='TEXT' runat = 'server' id = 'mystring' value = '" + str_value + "' />");
// Response.Write(sb.ToString());
}
else
{
sb.Append("<INPUT type='TEXT' runat = 'server' id = 'mystring' value = '' />");
}
ltlSearch.Text = sb.ToString();
But I need to check the value of the "mystring" text box inside pageload like,
if (!IsPostBack && !Page.IsAsync)
{
if (!string.IsNullOrEmpty(mystring.Value)) //NOT WORKING HOW TO GET the textbox value
{
//do something
}
}
Note: If I create the textbox control on page_init without a stringbuilder write method, the character with encoding displays on the textbox.
Any help?
Thanks
Venkat
Appending a string in your html, with runat="server" does not make it a server control. You will have to add your control dynamically from code behind, in page_init like this:
Add a PlaceHolder control:
<asp:PlaceHolder runat="server" ID="myPlaceHolder">
</asp:PlaceHolder>
Then this code in your Page_Init event to create the TextBox control:
protected void Page_Init(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "myTxt";
myPlaceHolder.Controls.Add(txt);
}
To get the Control from the Page_Load event:
TextBox txt = (TextBox)myPlaceHolder.FindControl("myTxt");
now you can access the Text property like you would with any other control:
txt.Text
Couple of things. Adding controls dynamically could be sometimes a painfully experience. Asp.net is not handling this control's viewstate right now. So you might receive some errors depending on what you are trying to accomplish. There are tons of tutorials online that will help you in this process.
Dynamically Create Controls in ASP.NET with Visual Basic .NET
TRULY UNDERSTANDING DYNAMIC CONTROLS (PART 1)
Add Controls to an ASP.NET Web Page Programmatically

Asp.net Dynamic link Button not raising event

I have a tabular data, in which at last column of every row a dynamic link button is added.
LinkButton link = new LinkButton();
link.Text = "Edit";
link.ID = dt.Rows[dt.Rows.IndexOf(dtRow)][0].ToString() + "|" + dt.Rows[dt.Rows.IndexOf(dtRow)][1].ToString();
link.ClientIDMode = System.Web.UI.ClientIDMode.AutoID;
cell.Controls.Add(link);
link.Click += new EventHandler(EditClicked);
The edit link is shown and on click it does the post back also But the event EditClicked is not fired at all.
Your problem is that you're dynamically creating your LinkButton and not recreating it again when your page is loaded.
If you dynamically create a control and then at postback, you don't create it again (in the Page_Load or preferably in the Page_Init) the event will not be fired.
One way to solve this is by using a hidden field:
When you dynamically create the linkbuttons, set a special value to a hidden field.
Then, in the Page_Load (in the if (IsPostback) ) check the hidden field, and if it has the special value - recreate all those controls again.

Make multiline textbox remember text input (auto complete)

A normal asp.net textbox will remember your old inputs - if you type something into a textbox and leave the page then come back, and type the same thing. The textbox will "auto complete" what you are typing by suggesting what you typed the last time.
I can see that if you set the Textmode property to "multiline" the textbox then loses it's auto complete. Like this:
<asp:TextBox ID="TextBox_Description" TextMode="MultiLine" MaxLength="500" runat="server"></asp:TextBox>
How do I add this funcitonality to my multiline asp Textbox or a TextArea? (multiline textboxes are rendered as textareas).
I am open to both asp.net specific solutions and javascript/jquery solutions.
You can retrieve what was in the multiline textbox and then cache it and on a postback use the cache to output what was used before.
// Get everything in the multiline text box and cache it
Cache["multilineValues"] = TextBox_Description.Text;
// Output what was written again through cache etc when the page loads after a postback.
//You would most likely put this in the Page_Load method.
if(IsPostBack)
{
if(Cache["multilineValues"] != null)
{
//Use what was written before
TextBox_Description.Text = (string)Cache["multilineValues"];
}
}

ASP.Net - repeating input boxes on the client side using Repeater

I have the following requirement for creating a user profile in my application:
User should be able to enter multiple phone numbers/email addresses in his profile.
The screen looks somewhat like this:
- By default, on page load a single textbox for phone and email are shown.
- User can click a "+" button to add additional numbers/addresses.
- On clicking the "+" button we need to add another textbox just below the first one. User can add as many numbers/addresses as he wants. On submit, the server should collect all numbers/emails and save it in DB.
I tried using the Repeater control to do this. On page_load I bind the repeater to a "new arraylist" object of size 1. So, this renders fine - user sees a single textbox with no value in it.
When he clicks the "+" button, I ideally want to use javascript to create more textboxes with similar mark-up as the first.
My questions are these:
Can I render the new textboxes anyway using js? I notice that the HTML rendered by the repeater control is somewhat complex (names/ids) etc. and it might not be possible to correctly create those controls on client-side.
If there is a way to do #1, will the server understand that these additional inputs are items in the repeater control? Say, I want to get all the phone numbers that the user entered by iterating over Repeater.DataItems.
Conceptually, is my approach correct or is it wrong to use the Repeater for this? Would you suggest any other approach that might handle this requirement?
Coming from a Struts/JSP background, I am still struggling to get a grip on the .NET way of doing things - so any help would be appreciated.
The repeater control may be a bit of overkill for what you're trying to accomplish. It is mainly meant as a databound control for presenting rows of data.
What you can do is to dynamically create the boxes as part of the Page_Load event (C#):
TestInput.aspx :
<form id="form1" runat="server">
<asp:HiddenField ID="hdnAddInput" runat="server" />
<asp:Button ID="btnPlus" OnClientClick="setAdd()" Text="Plus" runat="server" />
<asp:PlaceHolder ID="phInputs" runat="server" />
</form>
<script type="text/javascript">
function setAdd() {
var add = document.getElementById('<%=hdnAddInput.ClientID%>');
add.value = '1';
return true;
}
</script>
TestInput.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["inputs"] == null)
ViewState["inputs"] = 1;
if (hdnAddInput.Value == "1")
{
ViewState["inputs"] = int.Parse(ViewState["inputs"].ToString()) + 1;
hdnAddInput.Value = "";
}
for (int loop = 0; loop < int.Parse(ViewState["inputs"].ToString()); loop++)
phInputs.Controls.Add(new TextBox() { ID = "phone" + loop });
}
I ended up using a PlaceHolder to dynamically add the text boxes and a HiddenField to flag when another TextBox needed to be added. Since the IDs were matching, it maintains the ViewState of the controls during each postback.
Welcome to the hairball that is dynamically-added controls in ASP.NET. It's not pretty but it can be done.
You cannot add new fields dynamically using javascript because the new field would have no representation in the server-side controls collection of the page.
Given that the requirements are that there is no limit to the number of addresses a user can add to the page, your only option is to do "traditional" dynamic ASP.NET controls. This means that you must handle the adding of the control server-side by new-ing a new object to represent the control:
private ArrayList _dynamicControls = new ArrayList();
public void Page_Init()
{
foreach (string c in _dynamicControls)
{
TextBox txtDynamicBox = new TextBox();
txtDynamicBox.ID = c;
Controls.Add(txtDynamicBox);
}
}
public void AddNewTextBox()
{
TextBox txtNewBox = new TextBox();
txtNewBox.ID = [uniqueID] // Give the textbox a unique name
Controls.Add(txtNewBox);
_dynamicControls.Add([uniqueID]);
}
You can see here that the object that backs each dynamically-added field has to be added back to the Controls collection of the Page on each postback. If you don't do this, data POSTed back from the field has nowhere to go.
If you want to user the repeater, I think the easiest way is to put the repeater in a ASP.Net AJAX update panel, add the extra textbox on the sever side.
There are definitely other way to implement this without using repeater, and it maybe much easier to add the textbox using js.
No, but you can create input elements similar to what TextBox controls would render.
No. ASP.NET protects itself from phony data posted to the server. You can't make the server code think that it created a TextBox earlier by just adding data that it would return.
The approach is wrong. You are trying to go a middle way that doesn't work. You have to go all the way in either direction. Either you make a postback and add the TextBox on the server side, or you do it completely on the client side and use the Request.Form collection to receive the data on the server side.

Resources