Silverlight etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Silverlight etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

21 Ocak 2015 Çarşamba

Vb.Net ListBox Oluşturma ve ListBox Kullanımı | ListBox Constructor



Vb.Net ListBox Oluşturmak | ListBox Constructor

'Declaration
Public Sub New




The following code example demonstrates how to create a ListBox control 
that displays multiple items in columns and can have more than one item 
selected in the control's list. The code for the example adds 50 items 
to the ListBox using the Add method of the ListBox::ObjectCollection 
class and then selects three items from the list using the SetSelected 
method. The code then displays values from the 
ListBox::SelectedObjectCollection collection, through the SelectedItems 
property, and the ListBox::SelectedIndexCollection, through the 
SelectedIndices property. This example requires that the code is located 
in and called from a Form



Private Sub button1_Click(sender As Object, e As System.EventArgs)
     ' Create an instance of the ListBox. 
     Dim listBox1 As New ListBox()
     ' Set the size and location of the ListBox.
     listBox1.Size = New System.Drawing.Size(200, 100)
     listBox1.Location = New System.Drawing.Point(10, 10)
     ' Add the ListBox to the form. 
     Me.Controls.Add(listBox1)
     ' Set the ListBox to display items in multiple columns.
     listBox1.MultiColumn = True 
     ' Set the selection mode to multiple and extended.
     listBox1.SelectionMode = SelectionMode.MultiExtended

     ' Shutdown the painting of the ListBox as items are added.
     listBox1.BeginUpdate()
     ' Loop through and add 50 items to the ListBox. 
     Dim x As Integer 
     For x = 1 To 50
         listBox1.Items.Add("Item " & x.ToString())
     Next x
     ' Allow the ListBox to repaint and display the new items.
     listBox1.EndUpdate()

     ' Select three items from the ListBox.
     listBox1.SetSelected(1, True)
     listBox1.SetSelected(3, True)
     listBox1.SetSelected(5, True)

     ' Display the second selected item in the ListBox to the console.
     System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems(1).ToString())
     ' Display the index of the first selected item in the ListBox.
     System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices(0).ToString())
 End Sub



How to use a Listbox in VB.NET

How to use a Listbox in VB.NET


Select a Listbox from Visual Basic Express or Visual Studio’s Toolbox. Draw the frame of that ListBox and you should be ready to go. Your ListBox should be named ListBox1 if is your first one in your form.

ListBox


Then, in the code, we adjust the properties. I choose to do at the start of the form. You could do the same. I decided to do thing differently using the With function (it only change the presentation).



    Private Sub Form1_Load(sender As System.Object, e As System.EventArgsHandles MyBase.Load
        With ListBox1
            .Enabled = True 'if the listox is enable or disabled
            .Sorted = True ' if you want ti list sorted
            .BorderStyle = BorderStyle.Fixed3D ' the border style
            .Visible = True
            .ScrollAlwaysVisible = True 'presence of scroll all time
            .MultiColumn = False 'add a new column if number of items reach max height
        End With
    End Sub


When the ListBox is initialized, we can add words in it. In the same load function, I decided to add a lot of words. Nothing complicate and obviously some are identical.


Private Sub Form1_Load(sender As System.Object, e As System.EventArgsHandles MyBase.Load
        With ListBox1
            .Enabled = True 'if the listox is enable or disabled
            .Sorted = True ' if you want ti list sorted
            .BorderStyle = BorderStyle.Fixed3D ' the border style
            .Visible = True
            .ScrollAlwaysVisible = True 'presence of scroll all time
            .MultiColumn = False 'add a new column if number of items reach max height
        End With

        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")

    End Sub


ListBox1 is sorted alphabetically. That means all the “allo1” are all grouped together. “allo2” come after and so on. It will work each time you add a String in it.

If you execute the code right now, you will notice that no item is selected. This is perfect in most cases.


If you want to set an initial selection in ListBox1, you need to use SelectedIndex or SelectedItem.

Be careful. Each time you add an item or remove one from the ListBox, the indexes changes. Same thing if you sort an unsorted ListBox. So you can’t rely on the SelectedIndex property to get you result.


        ListBox1.SelectedIndex = 2 '0 is the first one, 2 is the third.



You could use SelectedItem to get the String stored in the ListBox. Again, the String may not be unique, so you have to be careful. If the user chooses something in the ListBox, you have to make sure your program will deal it correctly. Please notice the programme will always stop his selection on the first encountered.


        ListBox1.SelectedItem = "allo3" 'will always select the first he encounter




You could make the ListBox1 more interesting using the SelectionMode property.


        ListBox1.SelectionMode = SelectionMode.MultiSimple 'no need to use shift or ctrl, only space or left-click
        ListBox1.SelectionMode = SelectionMode.MultiExtended  'no need to use shift or ctrl with left-click


When SelectionMode is equal to SelectionMode.MultiSimple, then the user could simply use the mouse button to selecto or deselect the items in the ListBox1.

When SelectionMode is equal to SelectionMode. MultiExtended, the user need to use CTRL or SHIFT with the mouse button to select or deselects items.


We could also introduce a little event in the ListBox1. Lets say if the user choose an item in the ListBox, a little message box pops up and display the information. Just for fun or to validate our code.

Is pretty simple with Visual Basic Express 2010 or with Visual Studio 2010. Open your form with the design view  form1.vb [Design]. Double click on your ListBox1. You should see something like this.


    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgsHandles ListBox1.SelectedIndexChanged



    End Sub



Now put a MsgBox in the function and try to display something. Like SelectedIndex.


    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgsHandles ListBox1.SelectedIndexChanged

        MsgBox(ListBox1.SelectedIndex)

    End Sub


So when you change the selection in ListBox1, it will show the index (a number).

Your code should look something like this by now:


Public Class Form1
   
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgsHandles MyBase.Load
        With ListBox1
            .Enabled = True 'if the listox is enable or disabled
            .Sorted = True ' if you want ti list sorted
            .BorderStyle = BorderStyle.Fixed3D ' the border style
            .Visible = True
            .ScrollAlwaysVisible = True 'presence of scroll all time
            .MultiColumn = False 'add a new column if number of items reach max height
        End With

        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")


        ListBox1.SelectedIndex = 2 '0 is the first one, 2 is the third.
        ListBox1.SelectedItem = "allo3" 'will always select the first he encounter

        ListBox1.SelectionMode = SelectionMode.MultiSimple 'no need to use shift or ctrl, only space or left-click
        ListBox1.SelectionMode = SelectionMode.MultiExtended  'no need to use shift or ctrl with left-click

    End Sub
    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgsHandles ListBox1.SelectedIndexChanged

        MsgBox(ListBox1.SelectedIndex)



    End Sub


End Class



There is now a little flood in this code. When your start the code, the Msgbox is called before the form is completely loaded and chance are your get an empty Msgbox. This is not very sexy. We have to make this program a little more intelligent by putting a condition in the event function. Starting from now, I’ll quickly talk about it and forgive me if I am doing this too quickly. I’ll post another article later this week.



How to get rid of the Msgbox on load?

You have to bring 4 things in your code to make your code more intelligent:

-A condition in the function Listbox1 event
-A function that triggers the condition in the ListBox event.
-Declare a common variable available for both functions.
-Initialize that variable

Sorry if is not clear, is not always easy to explain something. Using this example might help.

The condition:


You need a if function or anything that could prevent your code to run the Msgbox. I love the if because is safe and simple to use.


    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgsHandles ListBox1.SelectedIndexChanged

        If form_onShow = True Then
            'MsgBox(ListBox1.SelectedItem.ToString)
            MsgBox(ListBox1.SelectedIndex)

        End If
        MsgBox(ListBox1.SelectedItem.ToString)
    End Sub


If the variable Form_onShow  is true, that meens the form is ready. Otherwise, nothing will happen.


The function that triggers the condition:


The form trigger a function when the form is completely loaded. That function is OnShown. That function is invisible in the form class, so you have to pick it and use it.

Here is the code:


    Protected Overrides Sub OnShown(e As System.EventArgs)
        MyBase.OnShown(e)
        form_onShow = True
    End Sub



Is best to simply copy and paste the code. No need to ask too much question here. The only thing we need to understand is that this function is triggered after the form is completely loaded. So is a good time to set the value form_onShow at true.

Declare a common variable available for both functions:

Every variable must be declared. Otherwise, the computer won’t be hable to know that is form_onShow. I suggest you to put the variable in the class Form1 but outside the functions.



Public Class Form1

    Private form_onShow As Boolean 'variable member of Form1

    Protected Overrides Sub OnShown(e As System.EventArgs)
        MyBase.OnShown(e)
        form_onShow = True
    End Sub



Initialize that variable:


Finally, you need to set an initial value to your and the best place to do it, is in the new function. The new function is like the OnShown function, is hidden. So you have to bring it. Check the sample and copy paste it in Visual Basic Express 2012 or Visual Studio 2012 (any edition will work)


    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        form_onShow = False
    End Sub


Finally, your code should look like this (without the error handling):


Public Class Form1

    Private form_onShow As Boolean 'variable member of Form1

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        form_onShow = False
    End Sub


    Protected Overrides Sub OnShown(e As System.EventArgs)
        MyBase.OnShown(e)
        form_onShow = True
    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgsHandles MyBase.Load
        With ListBox1
            .Enabled = True 'if the listox is enable or disabled
            .Sorted = True ' if you want ti list sorted
            .BorderStyle = BorderStyle.Fixed3D ' the border style
            .Visible = True
            .ScrollAlwaysVisible = True 'presence of scroll all time
            .MultiColumn = False 'add a new column if number of items reach max height
        End With

        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")
        ListBox1.Items.Add("allo1")
        ListBox1.Items.Add("allo2")
        ListBox1.Items.Add("allo3")
        ListBox1.Items.Add("allo4")
        ListBox1.Items.Add("allo5")


        ListBox1.SelectedIndex = 2 '0 is the first one, 2 is the third.
        ListBox1.SelectedItem = "allo3" 'will always select the first he encounter

        ListBox1.SelectionMode = SelectionMode.MultiSimple 'no need to use shift or ctrl, only space or left-click
        ListBox1.SelectionMode = SelectionMode.MultiExtended  'no need to use shift or ctrl with left-click

    End Sub
    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgsHandles ListBox1.SelectedIndexChanged

        If form_onShow = True Then
            'MsgBox(ListBox1.SelectedItem.ToString)
            MsgBox(ListBox1.SelectedIndex)

        End If
        MsgBox(ListBox1.SelectedItem.ToString)
    End Sub


End Class




Reference :



Object reference not set to an instance of an object 5

Object reference not set to an instance of an object 5

Complete the catch function


It is time to supplement the use of the catch function to make the error message more attractive. Here is the code:
''' <summary>
''' crash test and how to improve your coding
''' </summary>
''' <remarks></remarks>
Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgsHandles MyBase.Load

    End Sub
    ''' <summary>
    ''' pressing button1 will crash he program
    ''' this crash is the typical crashing type for all beginners
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgsHandles Button1.Click
        Dim aString() As String 'declare and array only


        Try
            'a crash will occur and the code won't be able to handle it
            MsgBox(aString(0)) ' you do something with the array and and array is nothing

        Catch ex As Exception
            MsgBox(ex.StackTrace, MsgBoxStyle.Exclamation, ex.Message) 'add basic error message here
        End Try

       
    End Sub
End Class



Adding arguments to the function Msgbox, we enrich the MsgBox window. Here's what happens when you run the function and the program crashes:
catch MsgBox

Now all the functions that you create will have the function Try and catch function. Throughout your catch function, I recommend you use the StackTrace property with the small exclamation icon. Yes, a picture is worth a thousand words, do not forget.
This technique protection code is very simple and only take 4 lines! Use it.
If you like this post, leave a comment or share it.


Object reference not set to an instance of an object 2

 Object reference not set to an instance of an object (part 2)


In a previous article, I demonstrated a simple and common error in programming: not create an object (or element).
When running the computer code, an error "fatal" occurs and the program stops. To solve the problem, I have not corrected, but I have rather isolated.
Here is an overview of the code from the previous article:

''' <summary>
''' crash test and how to improve your coding
''' </summary>
''' <remarks></remarks>
Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgsHandles MyBase.Load

    End Sub
    ''' <summary>
    ''' pressing button1 will crash he program
    ''' this crash is the typical crashing type for all beginners
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgsHandles Button1.Click
        Dim aString() As String 'declare and array only


        Try
            'a crash will occur and the code won't be able to handle it
            MsgBox(aString(0)) ' you do something with the array and and array is nothing
        Catch ex As Exception

        End Try

       
    End Sub
End Class



The function Try without a following error might occur:


Thus, the function Try isolates and captures the error preventing some way to stop whole the program. Keep in mind that Try do not correct the problem really. Indeed, the error in this case is an array is declared without assigning memory space for strings. A rookie mistake but also for the more experienced simply by accident.
But it was possible that the function Try detects an error may prevent the user. That is to say, prevent the user program so that it can then inform the designer of the computer code of the situation. Would this be the beginning of a quality control?
The answer to the question is yes. Yes, it is possible to capture the error. Yes the catch function which in French means  attraper .
I don’t want to make a big this article too long. I invite you to do this: add a Msgbox after the catch line.



        Try
            'a crash will occur and the code won't be able to handle it
            MsgBox(aString(0)) ' you do something with the array and and array is nothing
        Catch ex As Exception
            MsgBox(ex.Message) 'add basic error message here
        End Try

       


When you execute the code, instead of crashing the entire program, at least it will display a "controlled" message and finish the function.









Günün Fırsatı
isim isim isim isim isim isim