Dynamically adding Textbox in asp.net using C# - asp.net

I have written a code in which a textbox is dynamically added to a gridview cell. There is some default texts in the textbox. I want that when users will click on the textbox the default text will disappear and the user can then write anything on it only in number, i.e. the user will not be able to use letters or special characters.
Kindly let me know how to achieve this.
Code example
Gridview gv=new Gridview();
gv.DataSource=dt;
gv.DataBind();
Textbox t1 = new Textbox();
t1.Text="Outages if any(in mins)";
gv.Rows[0].Cells[0].Controls.Add(t1);
Need help after this, something like when user puts his cursor in the textbox , the default text will disappear , and if the user removes the cursor without writing anything , the default text will reappear. Also the default text should be a bit blurred
Thanks.

Try something like this
Textbox t1 = new Textbox();
t1.Attributes.Add("onclick", "if(this.value == 'default text') this.value = '';"
t1.Attributes.Add("onblur", "if(this.value == '') this.value = 'default text';" />
You could also use onfocus in case users use tab key
With this, using this.value, approach you don't need to know the client ID of the control.

Here is a post describing exactly what you are looking to do:
HowTo: including default text in a Textbox while enforcing server-side validation
The pertinent points are:
Adding javascript attribute to onfocus & and onblur:
txtName.Attributes.Add("onfocus","clearText()");
txtName.Attributes.Add("onblur","resetText()");
Adding the javascript to clear and repopulate the textbox:
function clearText() {
document.form1.txtName.value = ""
}
function resetText() {
if(document.form1.txtName.value == "")
document.form1.txtName.value = "(enter something here)"

You can do this. The easiest way is to use the ajaxControlToolkit. You can create controls dynamically. For example:
Dim mt As new TextBox
Dim newTest As New AjaxControlToolkit.TextBoxWatermarkExtender
With mt
.ID = "textBox1"
.TextMode = TextBoxMode.SingleLine
End With
With newTest
.ID = "TextBoxWatermarkExtender1"
.TargetControlID = mt.ClientID
.WatermarkText = "test"
End With
Then just add both controls to the gridview as you are doing with the textbox. If you are not using Ajax, you can add javascript to the control through codebehind but this is more difficult. Let me know if that is what you want to do and Ill add some code to show you how.
This should create a textbox control with an associated ajax TextBoxWaterMarkExtender.

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

pass data from code behind to jquery dialog

I am using below code to show jquery dialog, its working perfectly,
Sub OpenDialog(ByVal dialogId As String)
ScriptManager.RegisterStartupScript(Me, [GetType](), "openDialog", "$('#newPerson').dialog('open');", True)
End Sub
problem is that i wanted to pass some data from codebehind, i am using repeater control and binding repeater before opening dialog. it doesnt show any data on first click, when i click twice it show data in repeater control. any suggestion would be appreciated.
Regards
Use asp hidden fields,
Set there values in back end using this
HiddenField1.Value = "Your data";
& get them in JavaScript using this
document.getElementById('<%= HiddenField1.ClientID %>');

How to put values in textbox from listbox in jQuery MVC ASP.NET

I have one Listbox named "List1" and one button says "Append".
I have on textbox named "TextDescription".
I want to put the select values from the listbox to textbox on click of append button.
So can anyone tell me how to do this?
You could use the .val() function. So assuming you have a select with id="myselect" and a text input with id="mytext" you could do this:
var values = $('#myselect').val();
if (values != null) {
// concatenate the selected values with , so that we can add them to the textbox
$('#mytext').val(values.join(','));
}
And here's a live demo illustrating it in action.

want asp dropdownlist selection to make panel visible

I have an asp dropdownlist that I would like to make a panel visible if the selection contains a certain word- how would this be possible?
lets say you have dictionary like this
List<string> words = new List<string>();
words.Add("foo");
then onchange event of drop down list
string selectedText = ddlPanel.SelectedText;
foreach(var w in words)
{
if ( w.Contains(selectedText)
{
pnl.Visible = true;
}
}
<select onchange="if (this.options[this.selectedIndex].value.indexOf('foo') != -1) document.getElementById('panel').style.display = 'block'">
Place the panel you're looking to hide within an update panel, and use the dropdownlist change as a trigger to the updatepanel. On the update, check the dropdownlist's value and set the visibility.
Either that, or if you know the ID of the panel you can manually use javascript and bind the change event to a function that checks the values and shows/hides the panel accordingly.
Create dropDownlist with two items, "visible" and "not visible" or whatever suits you and make sure to set the autopostback property to true.
Then in vb write the following on page load:
If ddlMydropdown.Text = "visible" then
panelId.Visible = true
else
panelId.Visible = false
End If
If you code in c#, you can convert this vb code to c# over at developerfusion

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