Link to home
Start Free TrialLog in
Avatar of Dovberman
DovbermanFlag for United States of America

asked on

How to clear items from a listbox

I have populated a listbox named MyListBox.

How do I clear all the items from MyListBox?

Thanks,
ASKER CERTIFIED SOLUTION
Avatar of Paul Jackson
Paul Jackson
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dovberman

ASKER

I tried this.  The items remained visible.

How do I refresh the listbox display?
This is for asp.net ?

Please post some code and explain how you are populating the listbox and trying to clear it
Yes, this is for asp.net 4.0.

        var arrFiles = (from file in System.IO.Directory.GetFiles(strSourcePath, "*.txt")
                            orderby System.IO.Path.GetFileNameWithoutExtension(file) ascending
                            select new
                            {
                                FileName = System.IO.Path.GetFileNameWithoutExtension(file),
                                FullPath = file
                            }).ToArray();

            // Load listbox from array

            for (int i = 0; i < arrFiles.Count(); ++i)
            {
                lstFilesToDo.Items.Add(arrFiles(i)FileName);
            }

            int intTotal = arrFiles.Count();
            lstFilesToDo.DataSource = arrFiles;

// This is done by clicking a different button.
// Clear the listbox

            lstFilesToDo.Items.Clear();
     

            lblStatus.Text = "Daily Update Done for " + lblAvailableSource.Text;
            cmdFilesToDo.Focus();

// I could try a for loop for the Count property

int intSentCount = lstFilesSent.Items.Count;
for intCtr =0 to intSentCount

lstFilesSent.Items.Remove(lstFilesSent.Items(intCtr));
What event are you doing the population of the listbox in, if you are doing it in the page_load you need to check for if (!Page.IsPostback) before executing the code to stop it getting populated again when you click the button to clear the listbox.
If this is not the case then try setting the source property to null :

 lstFilesToDo.Items.Clear();
lstFilesToDo.Source = null;
protected void cmdFilesToDo_Click(object sender, EventArgs e)

        {
          // Load listbox from array

            for (int i = 0; i < arrFiles.Count(); ++i)
            {
                lstFilesToDo.Items.Add(arrFiles(I)FileName);
            }
lstFilesToDo.Source = null;  
Error: Source is not a listbox property.
sorry meant DataSource :

 lstFilesToDo.Items.Clear();
lstFilesToDo.DataSource = null;
lstFilesSent.Items.Clear();
            lstFilesToDo.Items.Clear();

Works now.  I rebuilt the solution in VS 2012.

Thanks,
Thank you.