ASP.NET Tutorial/ASP.net Controls/TextBox

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

asp:TextBox changed event (C#)

File: Default.aspx
<%@ Page language="c#" Inherits="EventTracker" CodeFile="Default.aspx.cs" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>Event Tracker</title>
</head>
<body>
  <form id="Form1" runat="server">
    <div>       
      <h1>Controls being monitored for change events:</h1>
      <asp:TextBox ID="txt" 
                   runat="server" 
                   AutoPostBack="true"
                   OnTextChanged="CtrlChanged" />
      <br /><br />
      <asp:CheckBox ID="chk" 
                    runat="server" 
                    AutoPostBack="true"
                    OnCheckedChanged="CtrlChanged"/>
      <br /><br />
      <asp:RadioButton ID="opt1" runat="server" GroupName="Sample"
       AutoPostBack="true" OnCheckedChanged="CtrlChanged"/>
      <asp:RadioButton ID="opt2" runat="server" GroupName="Sample"
       AutoPostBack="true" OnCheckedChanged="CtrlChanged"/>
      <br /><br /><br /> 
       <h1>List of events:</h1>
      <asp:ListBox ID="lstEvents" runat="server" Width="355px"
       Height="305px" /><br />      
    </div>
  </form>
</body>
</html>

File: Default.aspx.cs
using System;
using System.Collections;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class EventTracker : System.Web.UI.Page
{
  protected void Page_Load(object sender, System.EventArgs e)
  {
     Log("<< Page_Load >>");
  }
  private void Log(string entry)
  {
    lstEvents.Items.Add(entry);
    lstEvents.SelectedIndex = lstEvents.Items.Count - 1;
  }
  protected void Page_PreRender(object sender, System.EventArgs e)
  {
    Log("Page_PreRender");
  }
  protected void CtrlChanged(Object sender, EventArgs e)
  {
    string ctrlName = ((Control)sender).ID;
    Log(ctrlName + " Changed");
  }
}


Bind string value to asp:textBox (VB.net)

<script runat="server">
   dim strName as String = "A"
   dim myArray() as String = {"Hello", "World"}
   dim myString as String = "AA"
   sub Page_Load(Sender as Object, e as EventArgs)
      Page.DataBind()
   end sub
</script>
<html>
   <form runat="server">
   My Name is <%# strName %>
   <asp:Listbox datasource="<%# myArray %>" runat="server" />
  
   <asp:Textbox text="<%# myString.ToString %>" runat="server" />
   </form>
</html>


Check form input value and report error in case of empty input (VB.net)

<%@ Page Language="VB" %>
<script runat="server">
   sub Submit(Sender as Object, e as EventArgs)
      lblMessage.Text = ""
      if tbName.Text = "" then
         lblMessage.Text = "You forgot your name!<br>"
      end if
      if tbPhone.Text = "" then
         lblMessage.Text += "You forgot your phone!<br>"
      end if
      if tbEmail.Text = "" then
         lblMessage.Text += "You forgot your email!<br>"
      end if
      
      if lblMessage.Text = "" then
         lblMessage.Text = "Your information has been " & _
            "submitted!"
      end if
      
      
   end sub
</script>
<html><body>
   Please enter the following information.
   <asp:Label id="lblMessage" runat="server"/>
   <form runat="server">
      <table>
      <tr>
         <td width="250">Name* </td>
         <td width="150">
            <asp:TextBox id="tbName" runat="server"/>
         </td>
      </tr>
      <tr>
         <td>Address</td>
         <td>
            <asp:TextBox id="tbAddress" runat="server"/>
         </td>
      </tr>
      <tr>
         <td>Phone* (area code first)</td>
         <td>
            <asp:TextBox id="tbPhone" runat="server"/>
         </td>
      </tr>
      <tr>
         <td>Fax (area code first)</td>
         <td>
            <asp:TextBox id="tbFax" runat="server"/>
         </td>
      </tr>
      <tr>
         <td>Email*</td>
         <td>
            <asp:TextBox id="tbEmail" runat="server"/>
         </td>
      </tr>
      <tr>
         <td colspan="2">
            <asp:Button id="btSubmit" runat="server" Text="Submit" OnClick="Submit" />
         </td>
      </tr>
      </table>
      
      <i>An asterisk (*) indicates a required field.</i>
   </form>
</body></html>


Convert input in TextBox into decimal

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Simple Calculator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>The Simple Calculator</h1>
        First number:
        <asp:TextBox ID="txtFirst" runat="server" />  
        <br /><br />
        Second number:
        <asp:TextBox ID="txtSecond" runat="server" />  
        <br /><br />
        <asp:Button ID="btnAdd" runat="server"   
            OnClick="btnAdd_Click" Text="Add" />
        <br /><br />
        The answer is:
        <asp:Label ID="lblAnswer" runat="server" />  
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        decimal a = decimal.Parse(txtFirst.Text);
        decimal b = decimal.Parse(txtSecond.Text);
        decimal c = a + b;
        lblAnswer.Text = c.ToString();
    }
}


Extrapolate date values from the typed text

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
    Inherits="Default" %>
<!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>Extension Methods</title>
</head>
<body>
    <div id="pageContent">
        <form id="form1" runat="server">
            <asp:TextBox ID="TextBox1" runat="server" /> 
            <asp:Button ID="Button1" runat="server" Text="Test" OnClick="Button1_Click" />
            <hr />
            <h2>Next day is</h2>            
            <asp:Label ID="Label1" runat="server" /> 
        </form>
    </div>
    
</body>
</html>
 
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
public static class StringExtensions
    {
        public static bool IsInt32(this string content)
        {
            int number;
            bool result = Int32.TryParse(content, out number);
            return result;
        }
        public static bool IsDate(this string content)
        {
            DateTime date;
            bool result = DateTime.TryParse(content, out date);
            return result;
        }
        public static DateTime ToDate(this string content)
        {
            DateTime date;
            bool result = DateTime.TryParse(content, out date);
            if (result)
                return date;
            else
                return DateTime.MinValue;
        }
        public static int ToInt32(this string content)
        {
            int number;
            bool result = Int32.TryParse(content, out number);
            if (result)
                return number;
            else
                return Int32.MinValue;
        }
    }
public partial class Default : System.Web.UI.Page
{
    public void Button1_Click(object sender, EventArgs e)
    {
        string content = TextBox1.Text;
        if (content.IsDate())
        {
            DateTime date = content.ToDate();
            Label1.Text = date.AddDays(1).ToString("dd MMMM yyyy");
        }
        else
        {
            Label1.Text = "Not a valid date.";
        }
    }
}


Get input value from asp:textbox (VB.net)

<%@Page Language="VB" %>
<script runat="server">
Sub tbMessage_Change(Sender As Object,E As EventArgs)
    lblMessage.Text = "Hello" + tbMessage.Text
End Sub
</script>
<html>
<body>
     <%Response.Write("Our First Page")%>
    <form runat="server">
         Please enter your name:
         <asp:textbox id="tbMessage" OnTextChanged="tbMessage_Change" runat=server/>
         <asp:button id="btSubmit" Text="Submit" runat=server/>
         <asp:label id="lblMessage" font-size="20pt" runat=server/>
    </form>
</body>
</html>


Important properties, method and event of TextBox control

AccessKey:        specify a key that navigates to the TextBox control.
AutoCompleteType: associate an AutoComplete class with the TextBox control.
AutoPostBack:     post the form containing the TextBox back to the server automatically when the contents of the TextBox is changed.
Columns:          specify the number of columns to display.
Enabled:          disable the text box.
MaxLength:        specify the maximum length of data that a user can enter in a text box (does not work when TextMode is set to Multiline).
ReadOnly:         prevent users from changing the text in a text box.
Rows:             specify the number of rows to display.
TabIndex:         specify the tab order of the text box.
Wrap:             specify whether text word-wraps when the TextMode is set to Multiline.
Focus:            set the initial form focus to the text box.
TextChange:       Raised on the server when the contents of the text box are changed.

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        lblSearchResults.Text = "Search for: " + txtSearch.Text;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>TextBox AutoPostBack</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label
        id="lblSearch"
        Text="Search:"
        Runat="server" />
    <asp:TextBox
        id="txtSearch"
        AutoPostBack="true"
        OnTextChanged="txtSearch_TextChanged"
        Runat="server" />
    <hr />
    <asp:Label
        id="lblSearchResults"
        Runat="server" />
    </div>
    </form>
</body>
</html>


Set AutoCompleteType

<%@ Page Language="VB" %>
<!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 id="Head1" runat="server">
    <title>Show AutoComplete</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:Label
        id="lblFirstName"
        Text="First Name:"
        AssociatedControlID="txtFirstName"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtFirstName"
        AutoCompleteType="FirstName"
        Runat="server" />    
    <br /><br />    
    <asp:Label
        id="lblLastname"
        Text="Last Name:"
        AssociatedControlID="txtLastName"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtLastName"
        AutoCompleteType="LastName"
        Runat="server" />    
    <br /><br />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />    
    
    </div>
    </form>
</body>
</html>


Set textbox text value in button action

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="MyPage" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="The city name"></asp:Label>
        <asp:Label ID="note" runat="server" Text="Label"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Display" />
    </div>
    </form>
</body>
</html>

File: Default.aspx.vb

Partial Class MyPage
    Inherits System.Web.UI.Page
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        If Me.TextBox1.Text = "" Then
            Me.note.Text = "Please input the city name"
        Else
            Me.note.Text = "The input is:" & Me.TextBox1.Text
        End If
    End Sub
End Class


Set the focus to a TextBox

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load()
    {
        txtFirstName.Focus();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>TextBox Focus</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label
        id="lblFirstName"
        Text="First Name:"
        AssociatedControlID="txtFirstName"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtFirstName"
        AutoCompleteType="FirstName"
        Runat="server" />
    <br /><br />
    <asp:Label
        id="lblLastname"
        Text="Last Name:"
        AssociatedControlID="txtLastName"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtLastName"
        AutoCompleteType="LastName"
        Runat="server" />
    <br /><br />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />
    </div>
    </form>
</body>
</html>


Show AutoComplete

<%@ Page Language="C#" %>
<!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 id="Head1" runat="server">
    <title>Show AutoComplete</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label
        id="lblFirstName"
        Text="First Name:"
        AssociatedControlID="txtFirstName"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtFirstName"
        AutoCompleteType="FirstName"
        Runat="server" />
    <br /><br />
    <asp:Label
        id="lblLastname"
        Text="Last Name:"
        AssociatedControlID="txtLastName"
        Runat="server" />
    <br />
    <asp:TextBox
        id="txtLastName"
        AutoCompleteType="LastName"
        Runat="server" />
    <br /><br />
    <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />
    </div>
    </form>
</body>
</html>


TextBox can display different types of input fields depending TextMode property

The TextMode property accepts the following three values:
SingleLine: Displays a single-line input field.
MultiLine:  Displays a multi-line input field.
Password:   Displays a single-line input field in which the text is hidden.
<%@ Page Language="C#" %>
<!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 id="Head1" runat="server">
    <title>Show TextBox</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox
        id="txtUserName"
        TextMode="SingleLine"
        Runat="server" />
    <br /><br />
    <asp:TextBox
        id="txtPassword"
        TextMode="Password"
        Runat="server" />
    <br /><br />
    <asp:TextBox
        id="txtComments"
        TextMode="MultiLine"
        Runat="server" />
    </div>
    </form>
</body>
</html>


Use Cint to convert input value in asp:textbox to integer (VB)

<%@ Page Language="VB" %>
<script runat="server">
   Sub btSubmit_Click(Sender As Object, E As EventArgs)
     lblMessage.Text = Cint(tbNumber1.Text) * Cint(tbNumber2.Text)
   End Sub
</script>
<HTML>
<HEAD>
</HEAD>
<BODY>
<form runat="server">
    Number 1: <asp:textbox id="tbNumber1" runat=server/>
    Number 2: <asp:textbox id="tbNumber2" runat=server/>
    <asp:button id="btSubmit" Text="Submit" OnClick="btSubmit_Click" runat=server/>
    <asp:label id="lblMessage" font-size="20pt" runat=server/>
</form>
</BODY>
</HTML>


Use Convert.ToInt32 to convert input value in asp:textbox to integer (C#)

<%@ Page Language="C#" %>
<script runat="server">
  void btSubmit_Click(Object Sender, EventArgs e) {
     lblMessage.Text = (Convert.ToInt32(tbNumber1.Text) * Convert.ToInt32(tbNumber2.Text)).ToString();
  }
</script>
<HTML>
<HEAD>
</HEAD>
<BODY>
<form runat="server">
    Number 1: <asp:textbox id="tbNumber1" runat=server/>
    Number 2: <asp:textbox id="tbNumber2" runat=server/>
    <asp:button id="btSubmit" Text="Submit" OnClick="btSubmit_Click" runat=server/>
    <asp:label id="lblMessage" font-size="20pt" runat=server/>
</form>
</BODY>
</HTML>


Use if statement to check form input data (VB.net)

<script runat="server">
   sub Submit(Sender as Object, e as EventArgs)
      if tbFName.Text <> "" and not IsNumeric(tbFName.Text) then
         lblMessage.Text = "First name is incorrect!"
      end if
      if tbLName.Text <> "" and not IsNumeric(tbLName.Text) then
         lblMessage.Text = "Last name is incorrect!"
      end if
      if tbAddress.Text <> "" then
         lblMessage.Text = "Address is incorrect!"
      end if
 
      if tbCity.Text <> "" and not IsNumeric(tbCity.Text) then
         lblMessage.Text = "City is incorrect!"
      end if
 
      if tbState.Text <> "" and not IsNumeric(tbState.Text) then
        lblMessage.Text = "State is incorrect!"
      end if
  
      if tbZIP.Text <> "" and IsNumeric(tbZIP.Text) then
        lblMessage.Text = "ZIP is incorrect!"
      end if
  
      if tbPhone.Text <> "" then
        lblMessage.Text = "Success!"
      else
        lblMessage.Text = "Phone is incorrect!"
      end if
   end sub
</script>
<html><body>
   <form runat="server">
      <asp:Label id="lblMessage" runat="server" /><br>
      <asp:Panel id="Panel1" runat="server">
               First and last name:
               <asp:TextBox id="tbFName" runat="server" />
               <asp:TextBox id="tbLName" runat="server" />
               Email:
               <asp:TextBox id="tbEmail" 
                  runat="server" />
               Address:
               <asp:TextBox id="tbAddress" 
                  runat="server" />
               City, State, ZIP:
               <asp:TextBox id="tbCity" 
                  runat="server" />,
               <asp:TextBox id="tbState" runat="server"
                  size=2 />&nbsp;
               <asp:TextBox id="tbZIP" runat="server"
                  size=5 />
               Phone:
               <asp:TextBox id="tbPhone" runat="server"
                  size=11 />
               <asp:Button id="btSubmit" runat="server" 
                  text="Add" OnClick="Submit"/>
      </asp:Panel>
   </form>
</body></html>