数値のみ入力できるTextBoxにカンマも許容するプログラムを作りたいです。
数値の判定は、ソースは以下のリンクのような方法で書いています。
https://www.ipentec.com/document/document.aspx?page=csharp-textbox-limit-input-character
Keypress、Keydown両方の方法を教えていただけたら幸いです。
回答のほど、よろしくお願いいたします。
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。

回答1件
0
ベストアンサー
<Window x:Class="KeyPressTest1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:KeyPressTest1" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Grid> <TextBox x:Name="textbox_1" HorizontalAlignment="Center" Height="23" TextWrapping="NoWrap" VerticalAlignment="Center" Width="120" PreviewTextInput="Input_Test"/> </Grid> </Window>
C#
1using System.Windows; 2using System.Windows.Input; 3 4 5namespace KeyPressTest1 6{ 7 /// <summary> 8 /// MainWindow.xaml の相互作用ロジック 9 /// </summary> 10 public partial class MainWindow : Window 11 { 12 public MainWindow() 13 { 14 InitializeComponent(); 15 } 16 17 private void Input_Test(object sender, TextCompositionEventArgs e) 18 { 19 bool cut = false; 20 string check = "0123456789,\b"; 21 22 if (check.Contains(e.Text) == false) 23 { 24 cut = true; 25 } 26 27 e.Handled = cut; 28 } 29 }
WPFで考えました。バックスペースとカンマを許容します。
keypressだけで使える方法です。
formバージョン
C#
1using System.Linq; 2using System.Windows.Forms; 3 4namespace KeyPressTest2 5{ 6 public partial class Form1 : Form 7 { 8 public Form1() 9 { 10 InitializeComponent(); 11 } 12 13 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 14 { 15 bool cut = false; 16 string check = "0123456789,\b"; 17 18 if (check.Contains(e.KeyChar) == false) 19 { 20 cut = true; 21 } 22 23 e.Handled = cut; 24 } 25 } 26}
参考にしたページ
WPF:数値しか受け付けないTextBox
投稿2017/05/15 15:03
編集2017/05/15 15:25
退会済みユーザー
総合スコア0
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/05/16 12:59