古詩詞大全網 - 古詩大全 - vb中如何給listbox(列表框)添加編號

vb中如何給listbox(列表框)添加編號

由於list是但列數據表格,所以妳的要求其實用grid之類的是最容易實現的。用list也可以實現,但需要用代碼軟實現。

在窗體上添加1個ListBox,1個TextBOX,3個CommandButton控件。把ListBox的Sorted屬性改為True。該屬性為讓ListBox控件可以自動按字母排序。由於Sorted屬性,所以要把序號用00占位,否則排序結果將為

1、10、100、11、12……

然後粘貼如下代碼:

Private Sub Command1_Click()

On Error Resume Next

'添加壹個新信息

Me.List1.AddItem Right("00" & Me.List1.ListCount + 1, 3) & " " & Me.Text1.Text

'如果要插入在數據中則使用以下代碼,但需要再建立壹個text來寫插入的序號,即將Tmp替換成新text的值

'Dim Tmp As Integer

'Tmp = 10

'Tmp-1是將序號10變成列表裏的第9行,因為list是從0開始的.

'Me.List1.AddItem Right("00" & Tmp, 3) & " " & Me.Text1.Text, Tmp - 1

'For i = Tmp To Me.List1.ListCount - 1

' DoEvents

' Me.List1.List(i) = Right("00" & i + 1, 3) & " " & Right(Me.List1.List(i), Len(Me.List1.List(i)) - InStr(Me.List1.List(i), " ") - 2)

'Next

'將最後壹列數據變更為最大的數字

'Me.List1.List(Me.List1.ListCount - 1) = Right("00" & Me.List1.ListCount, 3) & " " & Right(Me.List1.List(Me.List1.ListCount - 1), Len(Me.List1.List(Me.List1.ListCount - 1)) - InStr(Me.List1.List(Me.List1.ListCount - 1), " ") - 2)

End Sub

Private Sub Command2_Click()

On Error Resume Next

'修改信息

Me.List1.List(Me.Text1.Tag) = Right("00" & Me.Text1.Tag + 1, 3) & " " & Me.Text1.Text

End Sub

Private Sub Command3_Click()

On Error Resume Next

'刪除信息

For i = CInt(Me.Text1.Tag) To Me.List1.ListCount - 1

DoEvents

Me.List1.List(i) = Right("00" & i + 1, 3) & " " & Right(Me.List1.List(i + 1), Len(Me.List1.List(i + 1)) - InStr(Me.List1.List(i + 1), " ") - 2)

Next

'刪除最後壹條數據

Me.List1.RemoveItem (Me.List1.ListCount - 1)

'由於是用list做序號,所以無法再使用RemoveItem方法

'Me.List1.RemoveItem (Me.Text1.Tag)

End Sub

Private Sub Form_Load()

'這個地方如果是1000,就要將 Right("00" & i, 3) 修改成 Right("000" & i, 4)

'最大數是多少就要修改下

For i = 1 To 100

Me.List1.AddItem Right("00" & i, 3) & " XXX" & i

Next

Me.Command1.Caption = "添加"

Me.Command2.Caption = "修改"

Me.Command3.Caption = "刪除"

End Sub

Private Sub List1_Click()

'將列表裏的信息去掉序號後顯示在文本中

Me.Text1.Text = Right(Me.List1.Text, Len(Me.List1.Text) - InStr(Me.List1.Text, " ") - 2)

'將序列號保存在Text的Tag屬性中

Me.Text1.Tag = Me.List1.ListIndex

End Sub