0

This seems pretty simple, and I'm not sure why its not working.

I have a button that when clicked adds an item to a list in the class:form.

public partial class Form1 : Form
{
    List<string> photoNames = new List<string>();


    private void button1_Click_1(object sender, EventArgs e)
    {
        //Hunce1947@superrito.com
        photoNames.Add("Ree");
        listBox1.DataSource = photoNames;
    }

However, whenever you click the item only a single item shows up. Why are multiple instances of "Ree" not showing up?

maccettura
  • 10,514
  • 3
  • 28
  • 35
Hunce1947
  • 3
  • 2

2 Answers2

0

Listbox don't detect the changes in the datasource. So set DataSource to null first, then reassign datasource again. This will work for you.

List<string> photoNames = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
    photoNames.Add("Ree");
    listBox1.DataSource = null;
    listBox1.DataSource = photoNames;                
}
Kaj
  • 806
  • 6
  • 16
  • How would this help? OP already sets the DataSource to `photoNames` _after_ they modified `photoNames`... – maccettura Jun 20 '18 at 20:59
  • @maccettura Well, as I explained, the listbox not catching the changes, you could run the code to see what results you'll get :) – Kaj Jun 20 '18 at 21:00
  • Setting listBox1.DataSource = null also sets DisplayMember to the empty string (but not ValueMember)... This could be confusing – maccettura Jun 20 '18 at 21:02
  • @maccettura Why not ValueMember ? would you explain a little ? – Kaj Jun 20 '18 at 21:06
  • just the way it is. Its better to use a `BindingList` instead of setting the datasource to null – maccettura Jun 20 '18 at 21:07
  • It'll be useful for sure with `ListChanged` as there is an event for listBox.DataSourceChanged, but I took the shortest way to do that. – Kaj Jun 20 '18 at 21:09
0

I do not have enough reputation to comment but I believe photoNames is a dataset, in that case I would say you you create a datatable and add rows.

 DataSet photoNames = new DataSet();

 DataTable dt = new DataTable("photoName");
 dt.Columns.Add(new DataColumn("pname", typeof(string)));

 ds.Tables.Add(dt);

and then instead of doing

photoNames.Add("Ree");

you can add ree as a row in the table of that dataset and bind it to your listbox like this:

 DataRow dr = dt.NewRow();
 dr["photoName"] = "Ree";
 dt.Rows.Add(dr);
 listBox1.DataSource = photoNames;
Pang
  • 9,564
  • 146
  • 81
  • 122
BlackMarker
  • 139
  • 12
  • Do you really need DataTable and DataSet to do that ? What a waste of resources. ! – Kaj Jun 20 '18 at 21:07
  • @Kaj As at when this question was posted, it was not specified that photoNames was a list. I dont have enough reputation to ask in the comment (read my answer) it was sorta safe to assume that it was a dataset as that's not completely out of context – BlackMarker Jun 21 '18 at 14:04