悟空-简单就好
.net企业级应用研究

考虑最复杂的情况
开发出最简单的实现


Word文档-资料管理系统!

导航

 
今天在做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        }
posted on 2005-09-13 14:18  新悟空  阅读(3139)  评论(8编辑  收藏  举报