Odd issue with textbox and ASP.NET - asp.net

This code was working properly before, basically I have a master page that has a single text box for searching, I named it searchBox. I have a method to pull the content of searchBox on form submit and set it to a variable userQuery. Here is the method:
Public Function searchString(ByVal oTextBoxName As String) As String
If Master IsNot Nothing Then
Dim txtBoxSrc As New TextBox
txtBoxSrc = CType(Master.FindControl(oTextBoxName), TextBox)
If txtBoxSrc IsNot Nothing Then
Return txtBoxSrc.Text
End If
End If
Return Nothing
End Function
The results are displayed on search.aspx. Now, however, if searchBox is filled and submitted on a page other than search.aspx, the contents of the text box are not passed through. The form is very simple, just:
<asp:TextBox ID="searchBox" runat="server"></asp:TextBox>
<asp:Button ID="searchbutton" runat="server" Text="search" UseSubmitBehavior="True" PostBackUrl="~/search.aspx" CssClass="searchBtn" />.

I think because you are using PostBackUrl, you are going to be required to use the "PreviousPage" identifier to reference your variable.
Another solution would to not use the PostBackUrl property and to capture the event within the user control (I'm assuming you are encapsulating this in one location) and then use the:
Response.Redirect("/search.aspx?sQuery=" & Server.URLEncode(searchBox.Text))
since you are not necessarily passing sensitive data, this should be acceptable as well.

I agree with Kyle as to why it doesn't work and the solution if you want to continue to access the value via the text control, but you can also pluck the form data out of the httprequest. I think like this (my asp.net is a bit rusty)
Request.Form[txtBoxSrc.UniqueID]
This plus other techniques (using the previouspage property) are documented here: http://msdn.microsoft.com/en-us/library/6c3yckfw(VS.80).aspx. It seems all you need to do is:
if (Page.PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
return SourceTextBox.Text;
}
}
Updated: Thanks to Jason Kealey for pointing out I needed to use UniqueID.

Related

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

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"];
}
}

Why is my RadioButtonList selectedValue empty?

I have a RadioButtonList:
<asp:RadioButtonList ID="rblMedicationTime" runat="server" onselectedindexchanged="rblMedicationTime_SelectedIndexChanged" DataSourceID="dtsMedicationTime" DataTextField="LookupItem" DataValueField="Id" AutoPostBack="true"></asp:RadioButtonList>
On page load, I want to select a radio button from the list and set its value, for which I have written this line of code:
rblMedicationTime.SelectedValue = clientMedicationSchedule.glTypeId.ToString();
The RadioButtonList is populating successfully, but the value is unable to be selected.
rblMedicationTime.SelectedValue is always "" when I debug the code.
You just need to use
string myValue = myRadioButtonList.SelectedItem.Value
The property object myRadioButtonList.SelectedItem contains all values from the selected item of a Radio Button list or a DropDown list
to set the value programmatically all you have to do is:
myRadioButtonList.SelectedIndex = 0;
You can see that you have several ways to Get but only one to Set:
myRadioButtonList.SelectedIndex --> Gets or Sets
myRadioButtonList.SelectedValue --> Gets
myRadioButtonList.SelectedItem --> Gets
You can't set the selected radiobutton with .SelectedValue, only with .SelectedIndex.
Check MSDN (at SelectedValue it says "Gets the value", at SelectedIndex is says "Gets or sets")
I think problem in !IsPostBack.
if (!IsPostBack)
{
string str = rblMedicationTime.SelectedValue;
}
First you should check !IspostBack
hello friend there is something another problem in your code because in my side this is running fine.
rblMedicationTime.SelectedValue = clientMedicationSchedule.glTypeId.ToString();
can u cehck that clientMedicationSchedule.glTypeId.ToString() this contain value or not.
and on page load u put selection code on if (!IsPostBack){} block.

general method to clearform in asp.net?

I am using master page with content pages. I want to write a genral method to clear textboxes and for dropdownlist set index to 0. Please guide on this.
A Server-Side Approach
If you want to clear the TextBoxes and DropDownLists on postback, you could recurse through the page's Controls collection and for each control see if it's a TextBox or DropDownList. Here's such a function in C#:
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
else if (ctrl is DropDownList)
((DropDownList)ctrl).ClearSelection();
ClearInputs(ctrl.Controls);
}
}
To use this you'd call ClearInputs passing in the control collection you want to search. To clear out all TextBoxes and DropDownLists on the page you'd use:
ClearInputs(Page.Controls);
A Client-Side Approach
An alternative tactic would be to use a client-side approach. Namely, use JavaScript to recurse through the DOM and clear/reset the textboxes and drop-downs on this page. The following JavaScript uses the jQuery library to simplify things:
function clearElements() {
$("input[type=text]").val('');
$("select").attr('selectedIndex', 0);
}
In a nutshell, it sets the value of all <input type="text" ... /> elements on the page to an empty string and sets the selectedIndex attribute of all <select> elements on the page to 0. I've created a script on JSFiddle.net to let you try out the script: http://jsfiddle.net/xs6G9/
For More Information
I wrote a blog entry on this topic with more information and discussion. See: Resetting Form Field Values in an ASP.NET WebForm.
Happy Programming!
<input type="reset"> is a simple solution client side.

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