Hi all!

In my Windows Forms Application (C# 2005), I am using ListBox but it have a problem when I remove item.
listBox.Items.RemoveAt(1); ---> Items collection cannot be modified when the DataSource property is set.

Note: It have just appeared when I used listbox.DataSource = dataTable;
If I dont use DataSource --> Everything is OK

For(int i=0; i<10; i++)
 listbox.item.Add(i.ToString());

listBox.Items.RemoveAt(1); ---> OK

Thanks in Adv

Hi,

The anwer is in your post. Simply don't use binding.

Regards,
Camilo

Hi,

The anwer is in your post. Simply don't use binding.

Regards,
Camilo

Microsoft supports thi datasource for us, why dont we use it? Could you explain to me?
If I dont use binding, How can I add values to this one like a ComboBox (DisplayMember, ValueMember)
Thanks adv

Hi,

"Microsoft supports thi datasource for us, why dont we use it? Could you explain to me?"

I think that the logic is like fallows. When you bind a DataTable to a ListBox what you get is a reference to the DataTable if you change any value in the ListBox you would be actually afecting any other object that is also bindded to that DataTable. So in my opinion that might be the motive. Also in OOP I don't think that is 'good practice' to change tha value of an object indirectly. (e.i Changing the value of the ListBox you are inded changing the value of the DataSet).

Hope this help,
Regards,
Camilo

Thanks Camilo,
But how can we add value into ListBox likes(DisplayMember, ValueMember)?

Hi,

I don't know if this is the best way to do it but my idea is to create a class for mapping the results that you get from the database and since the ListTextBox.Items.Add takes an object as parameter then you can pass an instance of that class that you had created.

Hope this help.
Camilo

Ah, that is an idea anyway. Thank you :)

Hi,

A littler late but this is all you need to do.

dataTable.Rows.RemoveAt(this.listBox.SelectedIndex);

of course like a said in one of the above posts this will update any other Control that is bound to that DataTable if any.

Regards,
Camilo

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.