0

I have problems to export selected listboxitems to a datatable,I want to have multiple selected plants to a datatable,Can you please help?

   int numberofplants = 0;

        foreach (ListItem li in lbxPlants.Items)
        {
            if (li.Selected)
            {
                numberofplants++;
                DataTable dtplants = new DataTable();
                dtplants.Columns.Add("Plants");
                DataRow drplants = dtplants.NewRow();
                drplants[0] = li.Value;
                dtplants.Rows.Add(drplants);

            }
        }
Asil Eris
  • 31
  • 3
  • 8
  • 2
    Probably you should take your DataTable initialization out of and before foreach. – Agent007 Oct 04 '12 at 08:45
  • Please specify the application, web/winform etc ?, I believe its a web application because of `ListItem` in your code – Habib Oct 04 '12 at 08:52

1 Answers1

1
int numberofplants = 0;

DataTable dtplants = new DataTable();
dtplants.Columns.Add("Plants");

foreach (ListItem li in lbxPlants.Items)
{
    if (li.Selected)
    {
        numberofplants++;

        DataRow drplants = dtplants.NewRow();
        drplants[0] = li.Value;
        dtplants.Rows.Add(drplants);
    }
}
Danilo Vulović
  • 2,983
  • 20
  • 31
  • C sharp doesnt allow me to write .SelectedItems.Also can you please help me about for the multiple selections,This example allow me to store one record. – Asil Eris Oct 04 '12 at 08:49
  • I believe since he is using `ListItem`, its a web application. Where `ListBox.SelectedItems` doesn't exist. You need to check it against `Items` – Habib Oct 04 '12 at 08:52
  • @AsilEris Are you using ListBox within WindowsForms c# – Danilo Vulović Oct 04 '12 at 08:55
  • Yes it is a web application,thats why doesnt allow me to write .SelectedItems. – Asil Eris Oct 04 '12 at 08:57
  • Hi Danilo,I think your code always change the dr[0] value,i mean doesnt put all the selections into a datatable,am i right? – Asil Eris Oct 04 '12 at 09:01
  • Ok. Just write code similar to yours, but DataTable initialization is outside foreach loop, according to @agent007 comment – Danilo Vulović Oct 04 '12 at 09:01
  • @AsilEris No, for every iteration within foreach loop, you create new DataRow object and set value – Danilo Vulović Oct 04 '12 at 09:05
  • maybe i am wrong but when i debug the dtplants from add watch,i get value {} but when i look at the rows property from add watch it says you have 2 rows. – Asil Eris Oct 04 '12 at 09:28
  • @AsilEris Check this answer: http://stackoverflow.com/questions/491555/how-can-i-easily-view-the-contents-of-a-datatable-or-dataview-in-the-immediate-w – Danilo Vulović Oct 04 '12 at 09:32