从列表框中删除项目会引发异常

时间:2013-06-24 08:18:39

标签: c# data-binding

我需要能够从列表框中删除项目但是当我按下删除功能并说“是”时我想要删除我得到此异常:Items collection cannot be modified when the DataSource property is set.

现在我想知道如何处理这件事。

namespace Flashloader
{
public partial class Form1 : Form
{
    private controllerinifile _controllerIniFile;
    private toepassinginifile _toepassingIniFile;
    // private Toepassinglist _toepassingList;


    private StringList _comPorts;

    public Form1()
    {
        InitializeComponent();


        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.WorkerSupportsCancellation = true;
        button4.Visible = false;



        _controllerIniFile = new controllerinifile();
        _toepassingIniFile = new toepassinginifile(_controllerIniFile.Controllers);

        // _toepassingList = new Toepassinglist(_controllerList).FromIniFile();
        _comPorts = new StringList();

        _applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
        _controllercombobox.DataSource = _controllerIniFile.Controllers;

        _applicationListBox.Refresh();
        _controllercombobox.Refresh();

        Settings settings = _toepassingIniFile.Settings;


        textBox3.Text = settings.Port;
        textBox4.Text = settings.Baudrate;

    }



    // File select Button and file directory
    private void button2_Click(object sender, EventArgs e)
    {
        appfile.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";


        {
            if (appfile.ShowDialog() == DialogResult.OK)
            {
                System.IO.StreamReader sr = new
                System.IO.StreamReader(appfile.FileName);
                sr.Close();
            }
        }
        String filedata = appfile.FileName;

        appfile.Title = ("Choose a file");
        appfile.InitialDirectory = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.ExecutablePath), @"C:\\\\Projects\\flashloader2013\\mainapplication\\");

        textBox1.Text = string.Format("{0}", appfile.FileName);

    }

    // textbox for the bootfile
    private void textBox2_TextChanged(object sender, EventArgs e)
    {

    }

    // start button for sending appfiles
    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
        serialPort1.Open();

        if (MessageBox.Show(appfile.FileName + " is selected and ready to be send,Are you sure you want to send the selected file?", "", MessageBoxButtons.YesNo) == DialogResult.No)
        {
            MessageBox.Show("The selected file will not be send.", "", MessageBoxButtons.OK);

        }
        else
        {
            button1.Visible = false;
            button4.Visible = true;
        }

        try
        {
            using (FileStream inputstream = new FileStream(OpenBoot.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 32 * 1024 * 1024, FileOptions.SequentialScan))
            {
                byte[] buffer = new byte[8 * 1024 * 1024];
                long bytesRead = 0, streamLength = inputstream.Length;

                inputstream.Position = 0;
                while (bytesRead < streamLength)
                {
                    long toRead = streamLength - bytesRead;
                    if (toRead < buffer.Length)
                        buffer = new byte[(int)toRead];

                    if (inputstream.Read(buffer, 0, buffer.Length) != buffer.Length)
                        throw new Exception("File read error");
                    bytesRead += buffer.Length;

                    serialPort1.Write(buffer, 0, buffer.Length);

                }
            }
        }
        catch
        {
            MessageBox.Show("No file selected");
        }

        StringList list = new StringList().FromFile(appfile.FileName);

        // Read file and put it in a list that will be sorted.
        foreach (String line in list)
        {
            list.Sort();
            serialPort1.Write(line);
        }

        MessageBox.Show("Bootfile and Applicationfile are send succesfully.");
    }

    // abort button for sending files
    private void button4_Click(object sender, EventArgs e)
    {
        backgroundWorker1.CancelAsync();

        button4.Visible = false;
        button1.Visible = true;

        progressBar1.Value = 0;
        timer1.Enabled = false;

        serialPort1.Close();
    }


    // backgroundworkers
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        DateTime start = DateTime.Now;
        e.Result = "";
        for (int i = 0; i < 100; i++)
        {
            System.Threading.Thread.Sleep(50);
            backgroundWorker1.ReportProgress(i, DateTime.Now);

            if (backgroundWorker1.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
        }

        TimeSpan duration = DateTime.Now - start;


        e.Result = "Duration: " + duration.TotalMilliseconds.ToString() + " ms.";

    }

    private void backgroundWorker1_ProgressChanged(object sender,
        ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;

        DateTime time = Convert.ToDateTime(e.UserState);

    }

    private void backgroundWorker1_RunWorkerCompleted(object sender,
        RunWorkerCompletedEventArgs e)
    {
        if (e.Cancelled)
        {
            MessageBox.Show("The task has been cancelled");
        }
        else if (e.Error != null)
        {
            MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
        }
        else
        {
            MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
        }

    }

    private void Boot_button_Click(object sender, EventArgs e)
    {
        OpenBoot.Filter = "Binary Files (.BIN; .md6; .md7)|*.BIN; *.md6; *.md7|All Files (*.*)|*.*";


        {
            if (OpenBoot.ShowDialog() == DialogResult.OK)
            {
                System.IO.StreamReader sr = new
                System.IO.StreamReader(appfile.FileName);
                sr.Close();
            }
        }
        String filedata = OpenBoot.FileName;

        OpenBoot.Title = ("Choose a file");
        OpenBoot.InitialDirectory = "C:\\Projects\\flashloader2013\\mainapplication\\Bootfiles";

        textBox2.Text = string.Format("{0}", OpenBoot.FileName);
    }

    // Saving the settings to the INI file.
    private void SaveSettings()
    {
        Toepassing toepassing = GetCurrentApplication();
        if (toepassing == null)
        {
            MessageBox.Show("No Application selected");
            return;
        }
        toepassing.Controller = (Controller)_controllercombobox.SelectedItem;
        toepassing.Lastfile = textBox1.Text;
        // toepassing.TabTip = 
        _toepassingIniFile.Save();
    }

    private Controller GetCurrentController()
    {
        int index = _controllercombobox.SelectedIndex;
        if (index < 0)
            return null;
        return _controllerIniFile.Controllers[index];
    }

    private Toepassing GetCurrentApplication()
    {
        int index = _applicationListBox.SelectedIndex;
        if (index < 0)
            return null;
        return _toepassingIniFile.ToePassingen[index];
    }


    private void typelistbox_SelectedIndexChanged(object sender, EventArgs e)
    {
        Toepassing toepassing = GetCurrentApplication();
        if (toepassing == null)
        {
            // TODO velden leegmaken
        }
        else
        {

            // appfile.InitialDirectory = Path.GetDirectoryName(controller.Lastfile);
            appfile.FileName = toepassing.Lastfile;

            textBox1.Text = toepassing.Lastfile;
            _controllercombobox.SelectedItem = toepassing.Controller;

        }
    }

    private void _controllercombobox_SelectedIndexChanged(object sender, EventArgs e)
    {
        Controller controller = GetCurrentController();
        if (controller == null)
        {
            // TODO velden leegmaken
        }
        else
        {
            textBox2.Text = controller.Bootfile;
        }
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void changeCurrentControllerToolStripMenuItem_Click(object sender, EventArgs e)
    {
        var controlleredit = new Controlleredit(_controllerIniFile);
        controlleredit.Show();
        Refresh();
    }

    private void addControllerToolStripMenuItem_Click(object sender, EventArgs e)
    {
        var controllersettings = new Newcontroller(_controllerIniFile);
        controllersettings.ShowDialog();
        _controllercombobox.DataSource = null;
        _controllercombobox.DataSource = _controllerIniFile.Controllers;
        // Refresh();
        // _controllercombobox.Refresh();         



    }

    private void newapplicationBtton_Click(object sender, EventArgs e)
    {
        var newapplication = new NewApplication(_toepassingIniFile);
        newapplication.ShowDialog();
        _applicationListBox.DataSource = null;
        _applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
    }

/////////////////////////////错误在这里///////////// ////////////////

    private void button3_Click(object sender, EventArgs e)
    {

        if (MessageBox.Show("You are about to delete application: "+ Environment.NewLine  + _applicationListBox.SelectedItem +Environment.NewLine + " Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
        {
            MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);

        }


        else if (this._applicationListBox.SelectedIndex >= 0)
            this._applicationListBox.Items.RemoveAt(this._applicationListBox.SelectedIndex);


    }
}

}

5 个答案:

答案 0 :(得分:2)

错误说得非常清楚:您必须从基础数据源中删除该项,您无法手动删除它。如果要手动删除/添加项目,则不应使用数据绑定,而是手动构建列表。

答案 1 :(得分:0)

尝试从数据源中删除,如下所示:

 string myobj = this._applicationListBox.SelectedValue.ToString();
 data.Remove(myobj );
 _applicationListBox.DataSource = null;
 _applicationListBox.DataSource = data;

答案 2 :(得分:0)

例外情况说,您无法直接从ListBox删除项目 - 您必须将其从基础DataSource中删除,然后重新绑定控件(如果它未绑定到BindingSource,例如)

private void button3_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("You are about to delete application: "+ Environment.NewLine  + _applicationListBox.SelectedItem +Environment.NewLine + " Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
    {
        MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
    }
    else if (this._applicationListBox.SelectedIndex >= 0)
    {
        var item = this.GetCurrentApplication();
        _toepassingIniFile.ToePassingen.Remove(item);
        _applicationListBox.DataSource = null;
        _applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
    }
}

你的代码很难阅读,所以我有点猜测类等,但它应该可以工作。

答案 3 :(得分:0)

正如其他人所说。您必须具有绑定到列表框的列表。您无法直接从列表框中删除。

您应该从列表中删除

private Toepassinglist _toepassingList

这是列表框的数据源。 删除你想要的项目......

this._toepassingList.Items.RemoveAt(this._applicationListBox.SelectedIndex);

答案 4 :(得分:0)

您可以从列表中删除:---

<强> ListName.Items.RemoveAt(现在的位置);