4

数値のみを受け入れるように datagridview 列をカスタマイズする方法はありますか。また、ユーザーが数字以外の文字を押した場合、現在のセルに何も入力する必要はありません。この問題を解決する方法はありますか

4

4 に答える 4

9
    private void gvAppSummary_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (gvAppSummary.CurrentCell.ColumnIndex == intRate)
        {
            e.Control.KeyPress += new KeyPressEventHandler(gvAppSummary_KeyPress);
        }
    }

    private void gvAppSummary_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
        {
            e.Handled = true;
        }
    }
于 2013-11-26T10:32:21.587 に答える
4

以前のソリューションでは、EditingControlShowing イベントに入るたびに、KeyPress で実行するイベントの «リスト» に KeyPressEvent を追加します。これは、KeyPress イベントにブレークポイントを設定することで簡単に確認できます。

より良い解決策は次のとおりです。

private static KeyPressEventHandler NumericCheckHandler = new KeyPressEventHandler(NumericCheck);
private void dataGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (dataGrid.CurrentCell.ColumnIndex == numericColumn.Index)
    {
        e.Control.KeyPress -= NumericCheckHandler;
        e.Control.KeyPress += NumericCheckHandler;
    }
}

そしてイベント NumericCheck:

private static void NumericCheck(object sender, KeyPressEventArgs e)
{
    DataGridViewTextBoxEditingControl s = sender as DataGridViewTextBoxEditingControl;
    if (s != null && (e.KeyChar == '.' || e.KeyChar == ','))
    {
        e.KeyChar = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
        e.Handled = s.Text.Contains(e.KeyChar);
    }
    else
        e.Handled = !char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar);
}
于 2015-02-11T10:09:49.093 に答える
3

datagridview Editingcontrolshowing を使用します..基本的にはこのように

private void dataGridView1_EditingControlShowing(object sender, 
    DataGridViewEditingControlShowingEventArgs e)    
{
String sCellName =  dataGridView1.Columns(e.ColumnIndex).Name; 
    If (UCase(sCellName) == "QUANTITY") //----change with yours
    {

        e.Control.KeyPress  += new KeyPressEventHandler(CheckKey);

     }
}

private void CheckKey(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) 
        && !char.IsDigit(e.KeyChar) 
        && e.KeyChar != '.')
    {
        e.Handled = true;
    }   
}

この CheckKey を改善できます...

于 2013-06-10T07:07:41.163 に答える