我正在尝试将项目向上/向下移动列表框,但不断收到错误,不知道如何修复它。错误与“ listBox1.Items.Remove(selected);
”有关
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace company1
{
public partial class Form1 : Form
{
List<Configuration> lines = new List<Configuration>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.listBox1.Items.Clear();
//Read in every line in the file
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
//string textfile = line;
string[] myarray = new string[] { "\\n" };
string[] parts = new string[9];
parts = line.Split(myarray, StringSplitOptions.RemoveEmptyEntries);
lines.Add(new Configuration(parts[0], int.Parse(parts[1]), int.Parse(parts[2])));
line = reader.ReadLine();
}
}
listBox1.DataSource = lines;
listBox1.DisplayMember = "CompanyName";
}
private void moveup_button_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItems.Count > 0)
{
object selected = listBox1.SelectedItem;
int indx = listBox1.Items.IndexOf(selected);
int totl = listBox1.Items.Count;
if (indx == 0)
{
listBox1.Items.Remove(selected);
listBox1.Items.Insert(totl - 1, selected);
listBox1.SetSelected(totl - 1, true);
}
else
{
listBox1.Items.Remove(selected);
listBox1.Items.Insert(indx - 1, selected);
listBox1.SetSelected(indx - 1, true);
}
}
}
private void movedown_button_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItems.Count > 0)
{
object selected = listBox1.SelectedItem;
int indx = listBox1.Items.IndexOf(selected);
int totl = listBox1.Items.Count;
if (indx == totl - 1)
{
listBox1.Items.Remove(selected);
listBox1.Items.Insert(0, selected);
listBox1.SetSelected(0, true);
}
else
{
listBox1.Items.Remove(selected);
listBox1.Items.Insert(indx + 1, selected);
listBox1.SetSelected(indx + 1, true);
}
}
}
}
}