c# 限制TextBox輸入類型


轉載:https://blog.csdn.net/qq_48705696/article/details/108929310

 1.為文本框添加KeyPress事件:

 

 2.輸入限制的原理:將輸入值轉化為ACSII的值進行限制,附上ACSII表

我猜你看不清這圖片,在圖片上右擊——>新標簽頁中打開圖片

(還不行的話:https://baike.baidu.com/item/ASCII/309296?fromtitle=ascii%E7%A0%81%E8%A1%A8&fromid=19660475&fr=aladdin

 

 3.原理大致明了了,接下來編程

    /// <summary>
    /// KeyPress事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        limit_txtinput(sender, e);
    }

    private void limit_txtinput(object sender, KeyPressEventArgs e)
    {
        //ACSII中48-57表示數字:0-9
        //ACSII中8表示退格鍵(刪除鍵)
        //ACSII中46表示小數點
        if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
            e.Handled = true;

        //小數點的處理。
        if ((int)e.KeyChar == 46) //小數點
        {
            if (this.Text.Length <= 0)
                e.Handled = true;   //小數點不能在第一位
            else
            {
                float f;
                float oldf;
                bool b1 = false, b2 = false;
                b1 = float.TryParse(this.Text, out oldf);
                b2 = float.TryParse(this.Text + e.KeyChar.ToString(), out f);
                if (b2 == false)
                {
                    if (b1 == true)
                        e.Handled = true;
                    else
                        e.Handled = false;
                }
            }
        }
    }

 

4.原作者的可輸入負號版本(只轉載,未經驗證)

    private void t_KeyPress(object sender, KeyPressEventArgs e)
    {            
        e.Handled = limit_txtinput(sender, e);
    }
 
    //限制txtBox的輸入內容僅可為數字和小數點(小數點不能是首位)
    private bool limit_txtinput(object sender, KeyPressEventArgs e)
    {
        //允許輸入數字、小數點、刪除鍵和負號
        if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e.KeyChar != (char)('-'))
            return true;
            
        if (e.KeyChar == (char)('-'))
        {
            if ((sender as TextBox).Text != "")
                return true;
        }
        //小數點只能輸入一次
        if (e.KeyChar == (char)('.') && ((TextBox)sender).Text.IndexOf('.') != -1)
            return true;
            
        //第一位不能為小數點
        if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "")
            return true;
            
        //第一位是0,第二位必須為小數點
        if (e.KeyChar != (char)('.') && e.KeyChar != 8 && ((TextBox)sender).Text == "0")
            return true;
            
        //第一位是負號,第二位不能為小數點
        if (((TextBox)sender).Text == "-" && e.KeyChar == (char)('.'))
            return true;
return false; }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM