Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

vb.net - How to sort values of textboxes in vb?

I have two groups of textboxes, A and B and these are created dynamically.

My program should work like this: 1. A textboxes have corresponding B textboxes. 2. Then, B textboxes should be sorted by their values in ascending order. 3. Based on that order, the A textboxes' values will be sorted also.

EX:

A                   B
5                   1
2                   0
3                   4
1                   5

Output is: 2 5 3 1

Please help me out. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create arrays of the textbox controls you have and then write a simple bubble sort. Bubble sort is slow, but more than fast enough for small amounts of data.

Dim arrA() As Textbox = {a1, a2, a3, a4, a5}
Dim arrB() As Textbox = {b1, b2, b3, b4, b5}
Dim Changed as Boolean
Do
  Changed = False
  For i = 0 to arrB.Count - 2 'Stop at the second to last array item because we check forward in the array
    If CInt(arrB(i).Text) > CInt(arrB(i + 1).Text) Then 'Next value is smaller than previous --> Switch values, also switch in arrA
      Dim Temp as String = arrB(i + 1).Text
      arrB(i + 1).Text = arrB(i).Text
      arrB(i).Text = Temp
      Temp = arrA(i + 1).Text
      arrA(i + 1).Text = arrA(i).Text
      arrA(i).Text = Temp
      Changed = True
    End If
  Next
Loop Until Changed = False 'Cancle the loop when everything is sorted

Now the textbox values are sorted and you can display the results whereever you want.

To display the values in the labels, say called l1-l5:

Dim arrL() as Label = {l1, l2, l3, l4, l5}
For i = 0 to 4
  arrL(i).Text = arrA(i).Text
Next

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...