毕设系列之ASP.NET中搜索出的字符串然后截取定长,和texttbox中的字符串进行比较


 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 using System.Collections;
 8 
 9 namespace WebApplication3.Transport
10 {
11     public partial class WebForm2 : System.Web.UI.Page
12     {
13         static string str1 = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["User"].ToString();
14         DataClasses1DataContext Den = new DataClasses1DataContext();
15         protected void Page_Load(object sender, EventArgs e)
16         {
17             
18         }
19 
20         protected void Button1_Click(object sender, EventArgs e)
21         {
22             int i = 0;
23             var count1 = (from deng in Den.businf where deng.status == 2 select deng.busid);//从数据库中搜索出指定的字段
24             foreach (var bus1 in count1)
25             {
26                 if(bus1.Replace(" ","")==TextBox1.Text.Replace(" ",""))//将数据库中找出来的数据和textbox中的数据进行比较
27                 {
28                     i++;
29                 }
30             }                           
31             TextBox2.Text = i.ToString();
32         }
33 
34         public ArrayList GetSeparateSubString(string txtString, int charNumber)//用于截取定长的字符串
35         {
36             ArrayList arrlist = new ArrayList();
37             string tempStr = txtString;
38             for (int i = 0; i < tempStr.Length; i += charNumber)
39             {
40                 if ((tempStr.Length - i) > charNumber)//如果是,就截取
41                 {
42                     arrlist.Add(tempStr.Substring(i, charNumber));
43                 }
44                 else
45                 {
46                     arrlist.Add(tempStr.Substring(i));//如果不是,就截取最后剩下的那部分
47                 }
48             }
49             return arrlist;
50         }
51     }
52 }

上面 的为后端代码:

前端代码就是一个textbox,还有一个botton,这里就不贴代码了,随便拖两个就能行。

这里需要解释的几个地方是,因为我们数据库中的nchar(n)中,括号里面的n是30,40这样变化的,然后我们从数据库中读取出来的时候,会造成一个局面就是我们的textbox中的字符串看起来和数据库中的值是一样的,然后我们比较出来却不相等,例如我上面的botton_click代码,如果没有replace语句,将读取出来字符串中的空格变成空,就不可能相等。

第二个需要解释的地方是:我们使用arraylist,必须引用using System.Collections;然后str.substring(i),就是将字符串str截取为定长为i的字符串了。