刷新VB.Net中的列表框

时间:2013-06-25 09:52:55

标签: vb.net

我想知道是否有办法刷新列表框中的续数

我正在使用代码添加数据

    ListBox1.Items.Add

我已设置为按钮,可使用以下代码删除所选数据:

     For i As Integer = ListBox1.SelectedIndices.Count - 1 To 0 Step -1
        ListBox1.Items.RemoveAt(ListBox1.SelectedIndices.Item(i))
    Next

说我的列表框是这样的

  1. 扎克
  2. 巴里
  3. John
  4. 尼克
  5. 布罗迪
  6. 如果我删除了说barry我怎么能让数字改变所以john将是2. etc

3 个答案:

答案 0 :(得分:1)

如果您对GDI +绘图有所了解,更有趣的方法是将ListBox的DrawMode设置为OwnerDrawFixed模式并收听ListBox的DrawItem事件,如下所示:

<强> C#

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    e.Graphics.DrawString((e.Index + 1).ToString() + ". " + listBox1.Items[e.Index].ToString(), listBox1.Font, Brushes.Black, e.Bounds);
    }

<强> VB.NET

Private Sub listBox1_DrawItem(sender As Object, e As DrawItemEventArgs)
    e.DrawBackground()
    e.Graphics.DrawString((e.Index + 1).ToString() & ". " & listBox1.Items(e.Index).ToString(), listBox1.Font, Brushes.Black, e.Bounds)
End Sub

向ListBox添加或删除任何项目将自动重新编号所有项目。

答案 1 :(得分:1)

BindingList在这里很有用,因为它可以监听列表中的更改。

例如,创建一个Person类并覆盖ToString函数以显示排名和名称。

Public Class Person
  Property Name As String
  Property Rank As Integer

  Public Overrides Function ToString() As String
    Return Rank & ". " & Name
  End Function
End Class

在表单中,声明列表并添加事件处理程序:

Private people As New BindingList(Of Person)

Public Sub New()
  InitializeComponent()

  AddHandler people.ListChanged, AddressOf people_ListChanged
  people.Add(New Person() With {.Name = "Zach"})
  people.Add(New Person() With {.Name = "Barry"})
  people.Add(New Person() With {.Name = "John"})
  people.Add(New Person() With {.Name = "Nick"})
  people.Add(New Person() With {.Name = "Brodie"})
  ListBox1.DataSource = people
End Sub

Private Sub people_ListChanged(sender As Object, e As ListChangedEventArgs)
  For i As Integer = 0 To people.Count - 1
    people(i).Rank = i + 1
  Next
End Sub

ListChanged事件只是更新每个成员在列表中插入的排名,这将自动更新ListBox,因为DataSource来自人员列表。

一个简单的删除按钮来测试列表,并在人员列表中自动更新排名,这会自动更新ListBox:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  If ListBox1.SelectedIndex > -1 Then
    people.Remove(ListBox1.SelectedItem)
  End If
End Sub

答案 2 :(得分:0)

您可以使用与ListBox结合的字符串列表。

Dim NamesList1 As New List(Of String)

Private Sub Form_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    NamesList1.AddRange({"Zach", "Barry", "John", "Nick", "Brodie"})
    FillListBoxItems()
End Sub

Private Sub FillListBoxItems()
    ListBox1.Items.Clear()

    For i As Integer = 0 To NamesList1.Count - 1
        ListBox1.Items.Add(i + 1 & ". " & NamesList1.Item(i))
    Next
End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    For i As Integer = ListBox1.SelectedIndices.Count - 1 To 0 Step -1
        NamesList1.RemoveAt(ListBox1.SelectedIndices.Item(i))
    Next

    FillListBoxItems()
End Sub