Solved

Help with adding data to listbox

Posted on 2012-12-27
13
265 Views
Last Modified: 2012-12-28
Hi,

My list box already contains data that was loaded using a dataset. When I try to add more data with the code below from a button click event:

 Dim item As String
        item = C1NSNA.Text
        C1NSN.Items.Add(item)

I receive the folowing error:

Items collection cannot be modified when the DataSource property is set.

How do i fix this error?

Victor
0
Comment
Question by:vcharles
  • 7
  • 6
13 Comments
 
LVL 25

Expert Comment

by:Luis Pérez
Comment Utility
When you set the data source for a ListBox or ComboBox via the .DataSource property, you are in fact telling .Net that your list control must show the items provided in the datasource, so you cannot manually add or remove items. So you got 2 possible solutions here:

1. Don't fill the list via the .DataSource property; instead of it, iterate the dataset in a for/next and add manually each item to the list.

or

2. If you still want to use the .DataSource, then add previously rows to the dataset with the values that you want in your list.

Hope that helps.
0
 

Author Comment

by:vcharles
Comment Utility
Can you please send me an example of option2.
0
 
LVL 25

Expert Comment

by:Luis Pérez
Comment Utility
Once you got your dataset filled with rows, you can do the following:

Dim row As DataRow = myDataSet.Tables(0).NewRow()
row("column 1") = "Value 1"
row("column 2") = 22
row("column 3") = "another value"
...
myDataSet.Tables(0).Rows.Add(row)

And after that, you can bind your Dataset with your ListBox.

Hope that helps.
0
 

Author Comment

by:vcharles
Comment Utility
Hi again,

I used the code  in part A of my web project and it works, any ideas why it doesn"t work in the Windows version? The listbox is populated same way in both web and Windows version,
as shown in part B.


Part A:
   Dim item As ListItem = New ListItem()
           item.Text = C1NSNA.Text
        C1NSN.Items.Add(item)


Part B

Dim _table As DataView = dtMaster.DefaultView
            _table.RowFilter = "NSN_ID in (" & keyNsn & ")"
            C1NSN.DataSource = _table
            C1NSN.DataTextField = "NSN"
            C1NSN.DataValueField = "NSN_ID"
            C1NSN.DataBind()
0
 
LVL 25

Expert Comment

by:Luis Pérez
Comment Utility
Because the Windows Forms ListBox inherits from System.Windows.Forms.ListControl and the Web Forms ListBox inherits from System.Web.BaseDataBoundControl, that obviously are not the same. If you open the Windows Forms ListBox link, you'll see in the MSDN page:
"When the DataSource property is set, a user cannot modify the items collection."

This behaviour doesn't happen in Web Forms.
0
 

Author Comment

by:vcharles
Comment Utility
I tried the code below but getting error message on the third line ( Tables is not a memeber of System.Data.Datatable)

  Dim row As DataRow = dtMaster.NewRow()
        row("NSN") = C1NSNA.Text
        dtMaster.Tables(0).Rows.Add(row)
        C1NSN.Items.Add(row)

The Listbox was loaded using the code below

Dim _table As DataView = dtMaster.DefaultView
            _table.RowFilter = "NSN_ID in (" & keyNsn & ")"
            C1NSN.DataSource = _table
            C1NSN.DataTextField = "NSN"
            C1NSN.DataValueField = "NSN_ID"
            C1NSN.DataBind()
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 25

Expert Comment

by:Luis Pérez
Comment Utility
Ok, you're binding without a dataset, but with a dataview that internally contains a datatable.

Instead of:
dtMaster.Tables(0).Rows.Add(row)
Add this:
dtMaster.Rows.Add(row)

You must do the above code before the .DataBind part.

And you don't need this:
C1NSN.Items.Add(row)

Hope that helps.
0
 

Author Comment

by:vcharles
Comment Utility
Hi,

I executed ViewDataB before the code as you suggested. i get no errors, but no data is copied to the listbox.

 Private Sub ViewDataB(ByVal keyLinkAid As String, ByVal keyNsn As String)
        Dim _table As DataView = dtMaster.DefaultView
        _table.RowFilter = "NSN_ID in (" & keyNsn & ")"
        C1NSN.DataSource = _table
        C1NSN.DisplayMember = "NSN"
        C1NSN.ValueMember = "NSN_ID"
    End Sub

 Private Sub ANSN_Click(sender As System.Object, e As System.EventArgs) Handles ANSN.Click
        ViewDataB(dtKeyMaster.Rows(0)(1), dtKeyMaster.Rows(0)(2))
        Dim row As DataRow = dtMaster.NewRow()
        row("NSN") = C1NSNA.Text
        dtMaster.Rows.Add(row)
    End Sub
0
 
LVL 25

Expert Comment

by:Luis Pérez
Comment Utility
Your approach is not right. Look:

1. First, you obtain your data from your source (I guess a database).
2. If you're going to bind this data to a list, once the binding is done then it's not possible to alter the items in the list. The list is "binded" to the source. So, if you want some items to appear that are not in your source (database), then manually add them to the datatable rows before doing the binding. So you cannot add items in the click of a button, because the binding has been done before.

Hope that helps.
0
 

Author Comment

by:vcharles
Comment Utility
I am using xml as a datasource. The data is loaded to the list box with following code:
          Dim _table As DataView = dtMaster.DefaultView
            _table.RowFilter = "NSN_ID in (" & keyNsn & ")"
            C1NSN.DataSource = _table
            C1NSN.DataTextField = "NSN"
            C1NSN.DataValueField = "NSN_ID"
            C1NSN.DataBind()

In click event of Add button if I have the following code to add a new row to dtMaster

'Add data to dtMaster datatable
  Dim row As DataRow = dtMaster.NewRow()
   row("NSN") = C1NSNA.Text

Ho do you rebind dtMaster to the listbox (C1NSN)?

'
0
 
LVL 25

Accepted Solution

by:
Luis Pérez earned 500 total points
Comment Utility
Try this:
- Add the new row to the datatable.
- Set again the datasource and do the databind as if it was the first time.

Hope that helps.
0
 

Author Comment

by:vcharles
Comment Utility
OK. I will try it and get back to you later.

Below is the code I am using with the listbox to save data from the listbox, but i think it might be simpler to use a similar approach with a Grid View to achieve the same goal. The Gridview was not used in the web version because it was not possible to add new rows, but I think for the Windows version, it might be a better approach. Thanks for your Help.

 For x As Integer = 0 To C1NSN.Items.Count - 1
                If CheckForNSNFix.Contains(C1NSN.Items(x).ToString) Then
                    For Each xnLink As Xml.XmlNode In xdNSN.SelectNodes("/Root/NSNTable[NSN='" & C1NSN.Items(x).ToString & "']")
                        NSN_ID = xnLink.SelectSingleNode("NSN_ID").InnerText
                        If NSN_ID <> "" Then
                            CD = NSN_ID
                            If u > 0 Then
                                num1 = num1 & "" & CD & ","
                            Else
                                num1 = CD & ","
                            End If
                            u = u + 1
                        End If
                    Next
                End If
            Next

            'Assign ID to data not already in XML file
            For x As Integer = 0 To C1NSN.Items.Count - 1
                If Not CheckForNSNFix.Contains(C1NSN.Items(x).ToString) Then
                    Dim xNew As XElement = New XElement(xtable)
                    xNew.Add(New XElement(xid, num))
                    xNew.Add(New XElement(curXYZ, C1NSN.Items(x)))
                    MyFix.Root.Add(xNew)
                    MyFix.Save((Application.StartupPath + "\App_Data\" & curXYZ & ".xml"))
                    If uu > 0 Then
                        num2 += num & ","
                    Else
                        num2 = num & ","
                    End If
                    uu = uu + 1
                    num = num + 1
                End If

            Next
            searchIdNSN = num1 & num2
0
 

Author Closing Comment

by:vcharles
Comment Utility
Thank You!
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now