Windows Azure Cloud Storage ermöglicht es Ihnen bereits ab 0,10€ pro GB/Monat die Vorteile der Cloud zu nutzen.
Willkommen bei dotnet-snippets.de! Snippet hinzufügen Login Registrieren
Snippets in der Datenbank: 1550 | Anzahl registrierter User: 1839 | Besucher online: 28
Hauptmenü
Home
Top Ten
Zufälliger Snippet
FAQs
.NET Community
dotnet-forum.de
dotnet-kicks.de
Social

RSS Feeds
Rss Alle Snippets
Rss C#
Rss VB.NET
Rss C++
Rss ASP.NET
Partner
Member of Microsoft Community Leader/Insider Program (CLIP)

numerische TextBox


Autor: Günther Foidl
Sprache: C#
Bewertung:
noch nicht bewertet
Anzahl der Aufrufe: 12778
  
Kick it on dotnet-kicks.de  

Beschreibung:

Nachfolgend ein Steuerelement das nur numerische Eingabe zulässt.

Abgelegt unter: TextBox, numerisch, Numerische TextBox, UserControl.



C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/******************************************************************************
 * UserControl: TextBox die nur numerische Eingaben akzeptiert.
 * 
 * Version:		1.1.0 (10.10.2008)
 * Erstellt am: 30.09.2008
 * Autor:		Günther M. FOIDL
 * Copyright:   Nach österreichischem Urheberrecht geltent.
 *              Die Verwendung/Lizenzierung obliegt dem Autor.
 *              
 * Änderungen:
 * 1.1.0		Hinzufügen von OnlyPositive
 *				Validierung und anzeige durch ErrorProvider
 *****************************************************************************/
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Forms;

namespace gfoidl.Tools.Controls
{
	/// <summary>
	/// TextBox die nur numerische Eingaben zulässt
	/// </summary>
	public class gfNumericTextBox : TextBox
	{
		#region Felder
		private ErrorProvider _errorProvider = new ErrorProvider();
		private bool _disposed = false;
		#endregion
		//---------------------------------------------------------------------
		#region Eigenschaften
		[DefaultValue(false)]
		[Description("Gibt an ob nur positive Werte erlaubt werden")]
		public bool OnlyPositive { get; set; }

		[DefaultValue(false)]
		[Description("Gibt an ob Leerzeichen akzeptiert werden")]
		public bool AllowSpace { get; set; }

		[DefaultValue(true)]
		[Description(
			"Gibt an ob das Einfügen über die Zwischenablage erlaubt ist")]
		public bool AllowPaste { get; set; }
		#endregion
		//---------------------------------------------------------------------
		#region Überschreibungen
		protected override void Dispose(bool disposing)
		{
			if (!_disposed)
			{
				_disposed = true;
				_errorProvider.Dispose();
				base.Dispose(disposing);

				GC.SuppressFinalize(this);
			}
		}
		//---------------------------------------------------------------------
		/// <summary>
		/// Erlaubt nur numerische Eingaben (HEX inklusive), 
		/// das Minuszeichen, den Dezimalpunkt und Bearbeitungszeichen
		/// (Backspace)
		/// </summary>
		/// <param name="e"></param>
		protected override void OnKeyPress(KeyPressEventArgs e)
		{
			base.OnKeyPress(e);

			NumberFormatInfo numberFormatInfo =
				CultureInfo.CurrentCulture.NumberFormat;
			string decimalSeperator = numberFormatInfo.NumberDecimalSeparator;
			string groupSeperator = numberFormatInfo.NumberGroupSeparator;
			string negativeSign = numberFormatInfo.NegativeSign;

			string keyInput = e.KeyChar.ToString();

			if (char.IsDigit(e.KeyChar))
			{
				// OK
			}
			else if ((keyInput.Equals(decimalSeperator)) ||
					(keyInput.Equals(groupSeperator)) ||
					(keyInput.Equals(negativeSign)))
			{
				// OK
			}
			else if (e.KeyChar == '\b')
			{
				// OK
			}
			else if (this.AllowSpace && e.KeyChar == ' ')
			{
				// OK
			}
			else
			{
				// ungültige Eingabe:
				e.Handled = true;
			}
		}
		//---------------------------------------------------------------------
		protected override void OnValidated(System.EventArgs e)
		{
			base.OnValidated(e);

			// Prüfen ob nur positive (0 inklusive) zulässig sind:
			if (this.Text.Contains("-") && this.OnlyPositive)
				_errorProvider.SetError(this, "Keine negativen Werte erlaubt");
			else
				_errorProvider.Clear();
		}
		//---------------------------------------------------------------------
		[Description(
			"Der dem Steuerelement zugeordnete Text. Nur numerische " +
			"Werte zulässig")]
		public override string Text
		{
			get
			{
				return base.Text;
			}
			set
			{
				bool digits = true;

				// Prüfen ob nur numerisch:
				foreach (char c in value)
					if (!(char.IsDigit(c) || c == '.' || c == ','))
					{
						digits = false;
						break;
					}

				// Wenn nur numerisch -> Eigenschaft setzen:
				if (digits)
					base.Text = value;
			}
		}
		//---------------------------------------------------------------------
		protected override void WndProc(ref Message m)
		{
			// Pasten prüfen:
			if (m.Msg == 0x0302)
			{
				foreach (char c in Clipboard.GetText())
				{
					if (!(char.IsDigit(c) || c == '.' || c == ','))
					{
						m.Result = IntPtr.Zero;
						return;
					}
				}
			}

			base.WndProc(ref m);
		}
		#endregion
		//---------------------------------------------------------------------
		#region Eigenschaften
		//---------------------------------------------------------------------
		/// <summary>
		/// Gibt den Inhalt als <c>int</c> zurück
		/// </summary>
		[Browsable(false)]
		public int IntValue
		{
			get
			{
				if (!string.IsNullOrEmpty(this.Text))
				{
					int i;
					if (int.TryParse(this.Text, out i))
						return i;
				}

				return 0;
			}
		}
		//---------------------------------------------------------------------
		/// <summary>
		/// Gibt den Inhalt als <c>float</c> zurück
		/// </summary>
		[Browsable(false)]
		public float FloatValue
		{
			get
			{
				if (!string.IsNullOrEmpty(this.Text))
				{
					float f;
					if (float.TryParse(this.Text, out f))
						return f;
				}

				return 0f;
			}
		}
		//---------------------------------------------------------------------
		/// <summary>
		/// Gibt den Inhalt als <c>double</c> zurück
		/// </summary>
		[Browsable(false)]
		public double DoubleValue
		{
			get
			{
				if (!string.IsNullOrEmpty(this.Text))
				{
					double d;
					if (double.TryParse(this.Text, out d))
						return d;
				}

				return 0;
			}
		}
		//---------------------------------------------------------------------
		/// <summary>
		/// Gibt den Inhalt als <c>decimal</c> zurück
		/// </summary>
		[Browsable(false)]
		public decimal DecimalValue
		{
			get
			{
				if (!string.IsNullOrEmpty(this.Text))
				{
					decimal d;
					if (decimal.TryParse(this.Text, out d))
						return d;
				}

				return 0;
			}
		}
		#endregion
	}
}
Sie haben Fragen zu diesem Snippet oder brauchen Hilfe bei der .NET Entwicklung?
Freundliche und kompetente Entwickler helfen Ihnen gern weiter im Forum für .NET Entwicklung.



Kommentare:
(Zum Schreiben von Kommentaren bitte anmelden.)

Günther Foidl schrieb am:  14.10.2008 15:45:01

Änderung:
if (this.Text.Contains("-"))

ersetzt durch:
if (this.Text.Contains("-") && this.OnlyPositive)
Günther Foidl schrieb am:  14.10.2008 17:47:36

Durch einen Tipp von Ralf Jansen wird jetz auch das Einfügen von der Zwischenablage geprüft.
Günther Foidl schrieb am:  02.12.2008 10:49:49

Das von dir vorgeschlagenen ist auch ein Möglichkeit - ich hab mich für diese Variante entschieden.

e.Handled = true; bedeutet dass das Ereignis als behandelt markiert wird und somit nicht weiterverarbeitet wird.


schlecht sehr gut
1 2 3 4 5 6 7 8 9 10
Nur angemeldete User können Snippets bewerten.