テキストボックスの値を取得する - ASP.NET

ASP.NET WebFormアプリケーションでテキストボックスの入力内容を取得するコードを紹介します。

概要

ASP.NET WebFormアプリケーションでテキストボックスの入力内容を取得するには、WebFormにテキストボックスコントロールを配置し、 テキストボックスコントロールのTextプロパティの値を参照することで入力内容を取得できます。

書式

(テキストボックスコントロール名).Text

プログラム例

ASP.NET WebFormアプリケーションを作成します。

UI

下記のWebフォームを作成します。

aspxファイルのコードは下記です。
SimpleTextBox.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SimpleTextBox.aspx.cs" Inherits="TextBoxDemo.SimpleTextBox" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
        </div>
    </form>
</body>
</html>

コード

下記のコードを記述します。
SimpleTextBox.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TextBoxDemo
{
  public partial class SimpleTextBox : System.Web.UI.Page
  {
    protected void Button1_Click(object sender, EventArgs e)
    {
      string InputStr = TextBox1.Text;
      Label1.Text = InputStr + " が入力されました。";
    }
  }
}

解説

Webフォームのボタンをクリックすると "Button1_Click()" メソッドが呼び出され処理が実行されます。
下記のコードでTextBox1のテキストボックスコントロールに入力された内容をInputStr変数に代入します。テキストボックスに入力した文字列が、InputStr変数に代入されます。
  string InputStr = TextBox1.Text;

Label1にInputStrの値を表示します。
  Label1.Text = InputStr + " が入力されました。";

実行結果

プロジェクトを実行します。Webブラウザで、SimpleTextBox.aspx ページを開きます。下図のページが表示されます。


テキストボックスに文字列を入力します。入力後[Button]ボタンをクリックします。


ボタンの下のラベルに文字列が表示されます。テキストボックスに入力した文字列が表示されることが確認できます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2021-01-18
作成日: 2020-03-17
iPentec all rights reserverd.