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

リストから削除できます:---

ListName.Items.RemoveAt(位置);

于 2013-06-24T08:33:05.953 に答える
0

他の人が言ったように。リストボックスにバインドされたリストが必要です。リストボックスから直接削除することはできません。

リストから削除する必要があります

private Toepassinglist _toepassingList

それがリストボックスのデータソースです。必要なアイテムを次のように削除します...

this._toepassingList.Items.RemoveAt(this._applicationListBox.SelectedIndex);
于 2013-06-24T08:25:39.903 に答える
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 に答える