zoukankan      html  css  js  c++  java
  • 限制文本框每行输入的字符数的C#代码

    今天在做IBM AS400 DB2和Excle加载项一个数据交换碰到的一个问题:
      限制每行输入的字符数。以下为源代码(textBox1命名保留为缺省为方便您测试使用)
    有用的两个函数:
    1、计算字符串的出现次数
    2、计算英汉混合字符串的字节数
     1private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
     2        {
     3            const int MaxLength=10;
     4            char chrKeyIn;
     5            string strLastCurrentFocus,strCurrentLine;
     6            int intCurrentLine;
     7            //计算当前行号
     8            strLastCurrentFocus=this.textBox1.Text.Substring(0,this.textBox1.SelectionStart);
     9            intCurrentLine=RepeatNumber (strLastCurrentFocus,"\r\n");
    10            //计算当前行的字节数
    11            chrKeyIn=e.KeyChar;
    12            strCurrentLine=this.textBox1.Lines[intCurrentLine-1]+chrKeyIn;
    13            if(LenB(strCurrentLine)>MaxLength)
    14            {
    15                if(false==System.Char.IsControl(chrKeyIn)  )
    16                    e.Handled =true;
    17            }

    18        }

    19        //计算字符串的出现次数
    20        private int RepeatNumber(string strSource,string strFind)
    21        {
    22            int intLastFind;
    23            int intNumber;
    24                intNumber=1;
    25            intLastFind=strSource.IndexOf(strFind);
    26            while(intLastFind>0)
    27            {
    28                intNumber++;
    29                intLastFind=strSource.IndexOf(strFind,intLastFind+1);
    30            }

    31            return intNumber;
    32        }

    33        //计算英汉混合字符串的字节数
    34        private int LenB(string strSource)
    35        {
    36            int intLength;
    37            char[] aryLenB=strSource.ToCharArray() ;
    38            intLength=0;
    39            foreach(char chrLenB in aryLenB)
    40            {
    41                if((int)chrLenB>255)
    42                    intLength+=2;
    43                else
    44                    intLength++;
    45            }

    46            return intLength;
    47        }
  • 相关阅读:
    java poi 操作
    java map 根据 map的value值进行排序
    Windows navcat 连接虚拟机mysql
    如何阻止Windows广告窗口弹出
    python gitlab 学习笔记
    Java的家庭记账本程序(D)
    《程序员修炼之道:从小工到专家》的阅读笔记(二)
    Java的家庭记账本程序(C)
    Java的家庭记账本程序(B)
    Java的家庭记账本程序(A)
  • 原文地址:https://www.cnblogs.com/fjwuyongzhi/p/235947.html
Copyright © 2011-2022 走看看