c# TextBox 查找替换模块
有
大小写匹配和
向上搜索的功能作为参数传进去
类里面的成员变量有:
private TextBox tb;
private int findCount = 0;
private int curFindIndex = 0; //为替换做准备
private int curFindLength = 0; //为替换做准备
private string findContext;
private string searchText;
1
private
void
FindText(TextBox tb, String findContext,
ref
int
findCount,
int
CurIndex,
bool
ingnoreCase,
bool
IsUp)
2
{
3
if (IsUp)
4
{
5
String LeftText = tb.Text.Substring(CurIndex);
6
int searchLength = tb.Text.Length - LeftText.Length - tb.SelectionLength;
7
searchText = tb.Text.Substring(0, searchLength);
8
}
9
else
10
{
11
searchText = tb.Text.Substring(CurIndex);
12
}
13
14
if (ingnoreCase)
15
{
16
searchText = searchText.ToUpper();
17
findContext = findContext.ToUpper();
18
}
19
int index = 0;
20
if (IsUp)
21
{
22
index = searchText.LastIndexOf(findContext);
23
}
24
else
25
{
26
index = searchText.IndexOf(findContext);
27
}
28
29
if (index != -1)
30
{
31
findCount += 1;
32
if(IsUp)
33
{
34
tb.SelectionStart = index;
35
}
36
else
37
{
38
tb.SelectionStart = index + CurIndex;
39
}
40
41
tb.SelectionLength = findContext.Length;
42
tb.Focus();
43
curFindIndex = tb.SelectionStart;
44
curFindLength = tb.SelectionLength;
45
}
46
else
47
{
48
if (findCount == 0)
49
{
50
MessageBox.Show("未找到以下指示文本", "济南网通");
51
}
52
else
53
{
54
MessageBox.Show("查找到了尽头", "济南网通");
55
}
56
}
57
}

2



3

4



5

6

7

8

9

10



11

12

13

14

15



16

17

18

19

20

21



22

23

24

25



26

27

28

29

30



31

32

33



34

35

36

37



38

39

40

41

42

43

44

45

46

47



48

49



50

51

52

53



54

55

56

57

1
private
void
btnFind_Click(
object
sender, EventArgs e)
2
{
3
bool IsUp = this.cbUp.Checked;
4
bool IgnoreCase = !this.cbBig.Checked;
5
FindText(tb, txtFind.Text, ref findCount, tb.SelectionStart + tb.SelectionLength, IgnoreCase,IsUp);
6
7
}
8

2



3

4

5

6

7

8

1
2
private
void
btnReplace_Click(
object
sender, EventArgs e)
3
{
4
if (curFindLength > 0)
5
{
6
string strTmp = tb.Text.Remove(curFindIndex, curFindLength);
7
tb.Text = strTmp.Insert(curFindIndex, txtReplace.Text);
8
curFindLength = 0;
9
}
10
}

2

3



4

5



6

7

8

9

10

1
private
void
btnReplaceAll_Click(
object
sender, EventArgs e)
2
{
3
if (cbBig.Checked)
4
{
5
tb.Text = tb.Text.Replace(txtFind.Text, txtReplace.Text);
6
}
7
else
8
{
9
string str1 = txtFind.Text.ToLower();
10
string str2 = txtFind.Text.ToUpper();
11
tb.Text = tb.Text.Replace(str1, txtReplace.Text);
12
tb.Text = tb.Text.Replace(str2, txtReplace.Text);
13
}
14
15
}

2



3

4



5

6

7

8



9

10

11

12

13

14

15

1
private
void
txtFind_TextChanged(
object
sender, EventArgs e)
2
{
3
findContext = txtFind.Text;
4
if (findContext != null && findContext.Length > 0)
5
{
6
btnFind.Enabled = true;
7
btnReplace.Enabled = true;
8
btnReplaceAll.Enabled = true;
9
}
10
else
11
{
12
btnFind.Enabled = false;
13
btnReplace.Enabled = false;
14
btnReplaceAll.Enabled = false;
15
}
16
}

2



3

4

5



6

7

8

9

10

11



12

13

14

15

16
