I want to generate a random alphanumeric string into password field when click a button.
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
code behind the button
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[8];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
txtPassword.Text = finalString.ToString();
this execute without any error.. but does not appear any text in textbox.
When I use
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
This works properly..
I have no any idea why my code is not working..
Please help me to solve this problem...
If you want to add text to password mode textfield then you need to write.
txtPassword.Attributes.Add("value", finalString.ToString());
Suggest to add using attributes
txtPassword.Attributes.Add("value", finalString.ToString());
please refer below link for more information on this.
http://www.tyronedavisjr.com/2008/05/23/aspnet-and-password-textbox-with-initial-value/
Related
This really is bizarre. I'm trying to implement the AutoCompleteExtender using a database. I enter the first character, let's say 'T' into the textbox, and the drop down results panel shows all of the page's source code (client side rather than server side), one character per line as seen in the image.
AutoComplete Results Screenshot
Incidentally, Google Chrome displays this straight away, while IE has a good think about it, saying localhost is not responding because it's running a long script.
If I then select any one of those characters it then displays the correct results beginning with 'T', though replaces the character I typed with whatever I selected.
I pulled the code from a tutorial on codeproject.com and apart from changing the textbox ID and a bit of ADO so it points to my database, it's identical.
I'll include the code. What's going wrong?
Now for some reason, it's not letting me post the code, regardless of how I format, but this is what I used. AutoComplete With DataBase and AjaxControlToolkit
It is very hard to give answer without seeing the code... try this
<asp:TextBox ID="txtSearchKey" runat="server" Width="350" AutoPostBack="true" OnTextChanged="txtSearchKey_TextChanged" />
<asp:TextBoxWatermarkExtender ID="weSearchKey" runat="server" Enabled="True" TargetControlID="txtSearchKey" WatermarkText="Search by Name" WatermarkCssClass="watermark" />
<asp:AutoCompleteExtender ServiceMethod="YourWebMethod" MinimumPrefixLength="3" CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" TargetControlID="txtSearchKey" ID="searchExtender" runat="server" FirstRowSelected="false" OnClientItemSelected="GetSelectedId" CompletionListCssClass="completionList" CompletionListItemCssClass="listItem" CompletionListHighlightedItemCssClass="itemHighlighted" CompletionListElementID="divCompletionListElement" />
<input type="hidden" id="hdnSelectedId" name="hdnSelectedId" value="" />
Have a javascript method to ensure selected item is captured
function GetSelectedId(source, eventArgs) {
var selectedId = eventArgs.get_value();
var e = document.getElementById('hdnSelectedId');
if (e) {
e.value = selectedId;
}
}
Create a WebMethod in your back end code that is configured in ServiceMethod property of AutoCompleteExtender
[ScriptMethod()]
[WebMethod]
public static List<string> YourWebMethod(string prefixText, int count)
{
var totalRecords = 0;
var searchResults = <<get your results here into a list or whatever container>>
//I used DataTable as a container here for searchResults
if (searchResults.Rows.Count == 0)
return new List<string>() { "No result found" };
//Create a List from your search results and return it
List<string> items = new List<string>();
foreach (DataRow searchResult in searchResults.Rows)
items.Add(AutoCompleteExtender.CreateAutoCompleteItem(searchResult["Name"].ToString(), searchResult["BuilderID"].ToString());
return items;
}
There is a similar thread about this. But I want to have a multiline TextBox with automatic width (fit width to the larger row).
With this code I can have a multiline TextBox (automatic height)
<div style="float:left; white-space:nowrap ">
<asp:TextBox style="display:inline; overflow:hidden"
ID="txt1"
runat="server"
Wrap="false"
ReadOnly="true"
TextMode="MultiLine"
BorderStyle="none"
BorderWidth="0">
</asp:TextBox>
</div>
<div style="float:left">
<asp:TextBox ID="txt2" runat="server" Text="Example textbox"></asp:TextBox>
</div>
Code behind:
txt1.Rows= text.Split("|").Length ' Sets number of rows but with low performance
txt1.Text = text.Replace("|", Environment.NewLine)
Once again, thanks for your help.
You could try a linq approach:
string[] rows = text.Split('|');
int maxLength = rows.Max(x => x.Length);
txt1.Rows = rows.Length;
txt1.Columns = maxLength;
If you are open to using plugins like jquery,
you should look at autoresize plugins.
These will resize as a user types too.
Check out one autoresize
$(document).ready(function(){
$('textarea').autosize();
});
Joel Etherton give me a real good working code example of how to resolve this using Linq, but unfurtenly I can't use Linq.
Multiline TextBox auto Width using Linq (Joel Etherton's solution):
C#
string[] rows = text.Split('|');
int maxLength = rows.Max(x => x.Length);
txt1.Rows = rows.Length;
txt1.Columns = maxLength;
VB
Dim rows() As String = text.Split("|")
Dim maxLength As Integer = rows.Max(Function(x) x.Length)
txt1.Rows = rows.Length
txt1.Columns = maxLength
text = text.Replace("|", Environment.NewLine)
txt1.Text = text
Multiline TextBox auto Width solution 2
To achieve this "manually", I did this method to know the larger row's lenght. Is not the most efficiente one, but It worked for me:
Dim textRows() As String = text.Split("|")
For Each row As String In textRows
row = row.Trim
textToDisplay = String.Format("{0}{1}{2}", textToDisplay, row, Environment.NewLine)
If row.Length > maxRowLenght Then
maxRowLenght = row.Length
End If
Next
txt1.Rows = textRows.Length
txt1.Columns = maxRowLenght
txt1.Text = textToDisplay
Suppose You have TextBox Control and the user enter any key into it. When the user enter the key ,on that event the key which is pressed stored into array and show him any another character.
Example . suppose i enter "x" but the textbox should display me "p".
Sounds like you need some JavaScript! With this code no matter what key the user presses, the textbox will type out ‘p.’ You could mix in a random letter generator if you really want to get crazy.
<script type="text/javascript">
function ScrewyKeypad(evt) {
var info = document.getElementById('<%= TextBox2.ClientID %>').value;
document.getElementById('<%= TextBox2.ClientID %>').value = info + 'p'
return false;
}
<asp:TextBox ID="TextBox2" runat="server" onkeypress="return ScrewyKeypad(event)" ></asp:TextBox>
And be sure to register the script in your page load event:
if (!IsPostBack)
{
TextBox2.Attributes.Add("onkeypress", "return ScrewyKeypad(event)");
}
My script isnt checking the requirement can u help me out with this?
I'm trying to make it run the script before it run the onclick to check if login is right.
<script type="text/javascript">
function checkform() {
var name = document.getElementsByTagName("UserName");
var pw = document.getElementsByTagName("Password");
if(name.charAt(0)!='s'){
document.getElementById("divMessage").innerHTML = "Please insert an S infront";
return false;
if(pw.length< 8 && pw.length>16){
document.getElementById("divMessage").innerHTML = "Please key in a longer password";
return false;
}
}else{
return true;
}
</script>
<asp:Button ID="btnLogin" class="button" runat="server" CommandName="Login"
OnClientClick ="return checkform()" onclick="btnLogin_Click" text="Login" />
You are trying to grab the controls based on tagNames. This way it could also return you a collection of controls as it says "document.get Elements ByTagName" Elements is plural. If your controls which you are trying to grab: UserName & Password are the actual ID in the Server controls use the following code:
<script type="text/javascript">
function checkform() {
var name = document.getElementById("<%=UserName.ClientID %>");
var pw = document.getElementById("<%=Password.ClientID %>");
if(name.charAt(0)!='s'){
document.getElementById("divMessage").innerHTML = "Please insert an S infront";
return false;
if(pw.length< 8 && pw.length>16){
document.getElementById("divMessage").innerHTML = "Please key in a longer password";
return false;
}
}else{
return true;
}
</script>
<asp:Button ID="btnLogin" class="button" runat="server" CommandName="Login"
OnClientClick ="return checkform()" onclick="btnLogin_Click" text="Login" />
In the case of the UserName & Password are not server controls by which I mean an asp control but rather its run on the client, for example its not a <asp:TextBox....
BUT a <input ... (which runs on the client) you could specify its id tag with the value of UserName and Password for the other one, with one change replace:
var name = document.getElementsByTagName("UserName");
var pw = document.getElementsByTagName("Password");
With:
var name = document.getElementById("UserName");
var pw = document.getElementById("Password");
Alternatively if you are trying to get it based on tagNames then you have to go thru the returned collection and find out which one is the control you want. For example if there is only one control with that name it will be the only item in the collection starting at 0 and if you go higher like 1 its out of range.
Hope this has been helpful to you.
When asp.net controls are rendered they have different id may be following are generating error
var name = document.getElementsByTagName("UserName");
var pw = document.getElementsByTagName("Password");
Set the ClientIDMode of the controls to Static.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx
this way the client ids will be the same as the server ones.
Once you have done that, change your js script to use getElementById();
Hope it helps.
I am trying to display contents of a folder in a hyperlink. I am using masterpage also. The hyperlinks are not shown into the content page. what to do for that?
I know in windows forms we can use like
TextBox.Location=new Point(100,100);
But how to do in web page...please anybody suggest me..
my coding in page_load is
protected void Page_Load(object sender, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/ProjectsUpload"));
int i = 0;
foreach (FileInfo fi in di.GetFiles())
{
HyperLink HL = new HyperLink();
HL.ID = "HyperLink" + i++;
HL.Text = fi.Name;
HL.NavigateUrl = "downloading.aspx?file=" + fi.Name;
Page.Controls.Add(HL);
Page.Controls.Add(new LiteralControl("<br/>"));
}
}
You can't add it directly to Page.Controls. You have to add it to the ContentPlaceHolder on the page.
Instead of dynamically creating controls, which is rather messy and error-prone, have you considered using an asp:Repeater control and binding the files directly to it? Something like:
<asp:Repeater ID="RepeaterFiles" runat="server">
<ItemTemplate>
<asp:HyperLink runat="server" Text='<%# Container.DataItem %>'
NavigateUrl='<%# String.Format("downloading.aspx?file={0}", Container.DataItem)%>' />
<br />
</ItemTemplate>
</asp:Repeater>
and in code behind:
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/ProjectsUpload"));
RepeaterFiles.DataSource = di.GetFiles();
RepeaterFiles.DataBind();
That way you can use declarative mark-up to control layout and keep the logic in your code-behind.
Put a PlaceHolder control on your page:
<asp:PlaceHolder runat="server" ID="ph" />
In your code behind write like:
HyperLink HL = new HyperLink();
HL.ID = "HyperLink" + i++;
HL.Text = fi.Name;
HL.NavigateUrl = "downloading.aspx?file=" + fi.Name;
ph.Controls.Add(HL);
ph.Controls.Add(new Literal { Text = "<br/>"});
I'm making use of the newly C# 3 feature on that last line to set the Text property.
Have you used the debugger to step through the loop to verify that it processes at least one file?
Instead of adding the links to Page.Controls, you could put a list control on the page, and then add each link within a list item. Then you'd know precisely where on the page they should appear.
Create a Panel or a Label in the Page's Content area, and add your HyperLinks into the Controls collection of the Panel.
(Stepping through the code to check whether the IIS App actually enumerates any files in the directory would help too.)