DataGridView只能输入数字型

本文介绍了一个使用 C# 编写的窗体应用程序中如何通过 DataGridView 控件实现对输入数据的限制,具体包括只允许用户输入数字及小数点,并演示了如何从 Excel 中读取数据并展示在 DataGridView 控件上。

 public partial class Form2 : Form
    {
        private DataGridViewTextBoxEditingControl EditingControl;

       
        private void EditingControl_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar.ToString()=="\b"||e.KeyChar.ToString()==".")
            {
                e.Handled = false; return;
            }
            if (!char.IsDigit(e.KeyChar)) e.Handled = true;
          
        }

        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            ds = GetExcelContent();
            dataGridView1.DataSource = ds.Tables[0].DefaultView;
        }

        private DataSet GetExcelContent()
        {
            string G_Str_ConnectionString = "SERVER=(local);DATABASE=db_GoodsManage;UID=sa;PWD=111111";
            SqlConnection myConn = new SqlConnection(G_Str_ConnectionString);
            string strCom = "SELECT * FROM v_UserView";
            myConn.Open();
            SqlDataAdapter myCommand = new SqlDataAdapter(strCom, myConn);
            //创建一个DataSet对象  
            DataSet myDataSet = new DataSet();
            //得到自己的DataSet对象  
            myCommand.Fill(myDataSet);
            //关闭此数据链接  
            myConn.Close();
            return myDataSet;
        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            EditingControl = (DataGridViewTextBoxEditingControl)e.Control;
            EditingControl.KeyPress += new KeyPressEventHandler(EditingControl_KeyPress);
        }
    }

转载于:https://www.cnblogs.com/heartinsky/archive/2009/04/10/1433066.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值