限制DataGridView 某個欄位輸入數字

限制DataGridView 某個欄位輸入數字

遇到就給他記錄下去.................小改一下程式碼做結合

順便記錄!!

 

   private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (this.dataGridView1.CurrentCell.ColumnIndex == 4)  //指定選擇的欄位索引 0 1.2.3.4
            {
                TextBox tb = (TextBox)e.Control; //沒指定的話就dataGridView1 內 textbox限制           
                keyin_mumber keyin = new keyin_mumber();
                tb.KeyPress += new KeyPressEventHandler(keyin.key_number);
                //tb.KeyPress += new KeyPressEventHandler(TextBoxDec_KeyPress);  
            }
        }

 

 

 

 

前輩的寫法..........................比精簡的....汗

 

 

private void TextBoxDec_KeyPress(object sender, KeyPressEventArgs e)
        {
            char key = e.KeyChar;
            int value = (int)key;
            if ((value >= 48 && value <= 57) || value == 46 || value == 8 || value == 43 || value == 45)
                e.Handled = false;
            else
                e.Handled = true;
        }

 

 

private void TextBoxDec_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    {
        e.Handled = true;
    }
}

 

 

 

因為懶惰所以寫成額外的類別之後可以繼續用 內容就套用一下前輩的吧

class keyin_mumber.cs

 
class keyin_mumber.cs
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    class keyin_mumber
    {
        public void key_number(object sender, KeyPressEventArgs e)
        {
                //內容填入前面的程式碼即可跑了
         }
        }
    }
}

 

 

 

相關參考資料

http://blog.csdn.net/todaywlq/article/details/2211831
http://www.dotblogs.com.tw/yc421206/archive/2010/10/15/18370.aspx
http://www.dotblogs.com.tw/chou/archive/2009/02/16/7189.aspx

http://www.dotblogs.com.tw/chou/archive/2009/07/31/9774.aspx

 

 

 

 

大家一起加入blogads 賺零用錢!!