1

我需要能够从列表框中删除项目,但是当我按下删除功能并说是我想删除时,我得到了这个异常: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);


    }
}

}

4

5 回答 5

2

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

于 2013-06-24T08:23:30.283 回答
0

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

 string myobj = this._applicationListBox.SelectedValue.ToString();
 data.Remove(myobj );
 _applicationListBox.DataSource = null;
 _applicationListBox.DataSource = data;
于 2013-06-24T08:24:00.707 回答
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;
    }
}

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

于 2013-06-24T08:24:13.353 回答
0

正如其他人所说。您必须有一个绑定到列表框的列表。您不能直接从列表框中删除。

您应该从列表中删除

private Toepassinglist _toepassingList

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

this._toepassingList.Items.RemoveAt(this._applicationListBox.SelectedIndex);
于 2013-06-24T08:25:39.903 回答
0

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

ListName.Items.RemoveAt(位置);

于 2013-06-24T08:33:05.953 回答