Solved

Help with adding data to listbox

Posted on 2012-12-27
13
271 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
13 Comments
 
LVL 25

Expert Comment

by:Luis Pérez
ID: 38723568
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
ID: 38723645
Can you please send me an example of option2.
0
 
LVL 25

Expert Comment

by:Luis Pérez
ID: 38723660
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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 

Author Comment

by:vcharles
ID: 38723784
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
ID: 38723819
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
ID: 38723876
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
 
LVL 25

Expert Comment

by:Luis Pérez
ID: 38723905
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
ID: 38724002
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
ID: 38724022
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
ID: 38724156
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
ID: 38724173
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
ID: 38724214
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
ID: 38726810
Thank You!
0

Featured Post

Business Impact of IT Communications

What are the business impacts of how well businesses communicate during an IT incident? Targeting, speed, and transparency all matter. Find out more in this infographic.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Removing Version of .NET in Windows 10 17 104
Error in Visual Project 10 42
vb.net code 9 24
I need to clear List Box in MVVM panel. 15 23
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

742 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