以下程序实现:在文本框输入内容,按回车键(Enter键)后,文本框中的内容输出到列表框。
1)在窗体上布置一个TextBox控件和一个ListBox控件
2)代码
Option ExplicitPrivate Sub Form_Load()
' 窗体启动时,清空Text1和List1
Text1Text = ""
List1Clear
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
' 如果按下了回车键(回车键的Ascii码为13)
If KeyAscii = 13 Then
Dim s As String
' 取出Text1中输入的内容并滤除前后的空格
s = Trim(Text1Text)
If s <> "" Then
' 如果Text1中输入的内容不为空,则添加到List1中
List1AddItem s
' 添加后,清空Text1
Text1Text = ""
End If
End If
End Sub
3)运行效果
窗体启动时
在Text1中输入,按回车后,输入的内容在List1中显示
实现这个功能的代码段:Dim a(10) as integer
for i=1 to 10
a(i)=i
print a(i);
next i你直接传一个数组进去,而且是一个结构体数组,arraysort怎么知道根据结构中的哪一个属性进行排序?放一个c#的代码你看看,VB和C#很相似的
class Program
{
static void Main(string[] args)
{
People[] p = new People[3]
{
new People{name="张三"},
new People{name="李四"},
new People{name="张二名"}
};
//重点传一个实现了IComparer接口的类进去,告诉ArraySort怎么排序
ArraySort(p, new PeopleCompare());
foreach (var item in p)
{
ConsoleWriteLine(itemname);
}
ConsoleReadKey();
}
}
//People结构体,换成类一样的
public struct People
{
public string name { get; set; }
}
//实现了IComparer接口的类
public class PeopleCompare : IComparer
{
public int Compare(object x, object y)
{
People p1 = (People)x ;
People p2 = (People)y;
return p1nameCompareTo(p2name);
}
}如果是固定数目的元素组合,那么用数个For循环嵌套来解决是很简单的,也不用判断重复。输入用的是文本框控件数组,输出的文本框的MultiLine属性要设为True,这样才能显示多行。从13个元素中取6个不重复元素的组合共有1716个。 Private Sub Command1_Click() Dim a(0 To 12) As Integer Dim i As Integer For i = 0 To 12 a(i) = Text(i)Text Next Text1Text = s(a) End Sub Private Function s(a() As Integer) As String Dim i1 As Integer Dim i2 As Integer Dim i3 As Integer Dim i4 As Integer Dim i5 As Integer Dim i6 As Integer Dim c As Integer Dim r As String For i1 = 0 To 12 - 5 For i2 = i1 + 1 To 12 - 4 For i3 = i2 + 1 To 12 - 3 For i4 = i3 + 1 To 12 - 2 For i5 = i4 + 1 To 12 - 1 For i6 = i5 + 1 To 12 r = r & a(i1) & "," & a(i2) & "," & a(i3) & "," & a(i4) & "," & a(i5) & "," & a(i6) & vbCrLf c = c + 1 DoEvents Next Next Next Next Next Next MsgBox c s = r End Function 但是这种算法的缺点是只能用于固定的数目,而且数目多的话程序写起来也很麻烦。下面再给一个可以算出任意数目元素组合的代码。 Private Sub Command1_Click() Dim a(0 To 12) As Integer Dim i As Integer For i = 0 To 12 a(i) = Text(i)Text Next Text1Text = s(a, 13, 6) End Sub Private Function s(a() As Integer, ByVal n As Integer, ByVal m As Integer) As String Dim b() As Integer Dim r As String Dim c As Integer ReDim b(0 To m - 1) ss a, n, b, m, 0, r, c MsgBox c s = r End Function Private Sub ss(a() As Integer, ByVal n As Integer, b() As Integer, ByVal m As Integer, ByVal d As Integer, r As String, c As Integer) Dim i As Integer If m = 0 Then For i = 0 To UBound(b) - 1 r = r & a(b(i)) & "," Next r = r & a(b(UBound(b))) & vbCrLf c = c + 1 Exit Sub End If If m > n Or n <= 0 Then Exit Sub b(d) = n - 1 ss a, n - 1, b, m - 1, d + 1, r, c ss a, n - 1, b, m, d, r, c End Sub
采纳哦
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)