キープレスイベントでのみ特定の列の数値のみを受け入れるデータグリッドビューを作成する必要があります。これを行う最善の方法はありますか?
100337 次
7 に答える
76
- EditorialControlShowingのイベントを追加します
- EditingControlShowingで、現在のセルが目的の列にあるかどうかを確認します。
- KeyPressの新しいイベントをEditingControlShowingに登録します(上記の条件が真の場合)。
- 以前にEditingControlShowingで追加されたKeyPressイベントをすべて削除します。
- KeyPressイベントで、キーが数字でない場合は入力をキャンセルすることを確認してください。
例:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
于 2013-02-01T03:35:05.097 に答える
35
次のようにDataGridView.CellValidating Eventを使用する必要があります。
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 1) // 1 should be your column index
{
int i;
if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
{
e.Cancel = true;
label1.Text ="please enter numeric";
}
else
{
// the input is numeric
}
}
}
于 2012-09-28T19:34:45.753 に答える
4
他の人が指摘したように小数点以下の桁数が必要でない限り、与えられた答えは優れています。このイベントでは、検証を拡張し、以下の using および vars を追加して、小数点記号のカルチャ変数値を取得する必要があります。
using System.Globalization;
NumberFormatInfo nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
char decSeperator;
decSeperator = nfi.CurrencyDecimalSeparator[0];
検証を次のように拡張します。
if (!char.IsControl(e.KeyChar) && !(char.IsDigit(e.KeyChar)
| e.KeyChar == decSeperator))
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == decSeperator
&& (sender as TextBox).Text.IndexOf(decSeperator) > -1)
{
e.Handled = true;
}
于 2015-10-12T11:48:40.263 に答える
2
Private WithEvents txtNumeric As New DataGridViewTextBoxEditingControl
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
txtNumeric = CType(e.Control, DataGridViewTextBoxEditingControl)
End Sub
Private Sub txtNumeric_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtNumeric.KeyPress
If (DataGridView1.CurrentCell.ColumnIndex > 0) Then
If (Not Char.IsControl(e.KeyChar) And Not Char.IsDigit(e.KeyChar) And Not e.KeyChar = ".") Then
e.Handled = True
Else
'only allow one decimal point
If (e.KeyChar = "." And txtNumeric.Text.Contains(".")) Then
e.Handled = True
End If
End If
End If
End Sub
于 2015-08-17T11:27:00.267 に答える