代码改变世界

关于ListBox和DataTable的一点儿心得

2005-06-02 11:59  胖子  阅读(2654)  评论(1编辑  收藏  举报

ListBox的多选
这个比较简单,通过循环就可以搞定。
首先设置ListBox的选择模式为多行:

Me.ListBox1.SelectionMode = ListSelectionMode.Multiple

然后是处理选择:
If Me.ListBox1.SelectedIndex > -1 Then
    
Dim sValue As String
    
Dim sText As String
    
For i As Integer = 0 To Me.ListBox1.Items.Count() - 1
        
If Me.ListBox1.Items(i).Selected Then
            sValue 
&= Me.ListBox1.Items(i).Value & ","
            sText &= Me.ListBox1.Items(i).Text & ","
        End If
    
Next
    
Me.Label1.Text = "You choose: " & Left(sValue, sValue.Length - 1)
    
Me.Label2.Text = "You choose: " & Left(sText, sText.Length - 1)
Else
    
Me.Label1.Text = "You have no choose!"
    Me.Label2.Text = ""
End If


这样就可以将ListBox里的选择内容变成以 ","  隔开的字符串。


ListBox 的删除
ListBox提供了两种删除Item的方法,Remove 和 RemoveAtt(Clear方法是移除了所有的对象,不能算是删除具体的Item)
删除单个的选择比较容易,下面介绍一个删除多个选择的方法,当然也能删除单个了

Do Until Me.ListBox1.SelectedIndex < 0
    
Me.ListBox1.Items.RemoveAt(Me.ListBox1.SelectedIndex)
Loop


DataTable
和上面的ListBox有点儿关系,在工作中遇到的情况。
要求选择不同的人员到不同的ListBox中,每个ListBox代表一种角色。
所添加的人不能同时出现在两个及其以上的ListBox中,也就是说每个人只能是一种角色。看下面的代码:
Private Sub Check()
    
Dim strMsg As String = ""
    Dim dt As New DataTable
    
Dim colID As DataColumn
    
    
'动态生成Column
    '
    '也可以下面的语句
    'Dim colID As DataColumn = New DataColumn("id", GetType(String))
    '
    colID = New DataColumn("id")
    colID.DataType 
= GetType(String)
    
'这句话是关键,设置该列为unique约束,不能插入重复的值
    colID.Unique = True 

    dt.Columns.Add(colID)

    
If LstInsert(Me.ListBox1, dt) Then
        
Me.Label3.Text = ""
    End If

    dt.Clear()
    dt.Dispose()

End Sub


Private Function LstInsert(ByVal lst As UI.WebControls.ListBox, ByRef dt As DataTable) As Boolean
    
'生成DataRow
    Dim myNewRow As DataRow
    
Dim flag As Boolean = True
    
For i As Integer = 0 To Me.ListBox1.Items.Count - 1
        myNewRow 
= dt.NewRow()
        myNewRow(
"id"= Me.ListBox1.Items(i).Value
        
Try
            dt.Rows.Add(myNewRow)
        
Catch ex As Exception
            flag 
= False
            
'Me.ListBox1.ClearSelection()
            Me.ListBox1.Items(i).Selected = True
            
Me.Label3.Text &= Me.ListBox1.Items(i).Text & " 重复!不能一人身兼多职! "
            'Exit For
        End Try
    
Next

    
Return flag

End Function

动态生成Unique列的方法适合于一次性插入不同数据的执行前检验。

以上代码为测试使用,只是实现了功能要求,具体要用的话还要再酌情处理一下。