我有一个带有显示内容的列表框的Windows窗体应用程序,我希望能够在单击按钮时上下移动列表框中的项目。此时列表框中的项目存储在文本文件中,该文件在应用程序启动时加载到配置类中。如何上/下移动项目并更改文本文件中的顺序?
我的主要申请表格代码:
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 = reader.ReadLine();
while (line != null)
{
string[] array = new string[] { "\\n" };
string[] parts = new string[3];
parts = line.Split(array, 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";
}
}
}
配置类文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace company1
{
class Configuration
{
string _CompanyName;
int _Employees;
int _Half;
public Configuration(string companyname, int number_of_Employees, int half)
{
_CompanyName = companyname;
_Employees = number_of_Employees;
_Half = half;
}
//program properties and validation
public string CompanyName
{
set
{
_CompanyName = value;
}
get
{
return _CompanyName;
}
}// End of levelname validation
//program properties and validation
public int EmployeesNumber
{
set
{
_Employees = value;
}
get
{
return _Employees;
}
}// End of levelname validation
//program properties and validation
public int Half
{
set
{
_Half = value;
}
get
{
return _Half;
}
}// End of levelname validation
}
}
任何帮助表示赞赏,已经尝试了几天才能让它发挥作用。
答案 0 :(得分:0)
// change the items in source list
var tmpLine = lines[10];
lines[10] = lines[9];
lines[9] = tmpLine;
// refresh datasource of listbox
listBox1.DataSource = null;
listBox1.DataSource = lines;
答案 1 :(得分:0)
您可以为列表定义扩展方法,以便根据索引移动项目:
public static class ExtensionClass
{
public static void Move<T>(this List<T> list, int index1, bool moveDown = true)
{
if (moveDown)
{
T temp = list[index1];
list[index1] = list[index1 + 1];
list[index1 + 1] = temp;
}
else
{
T temp = list[index1];
list[index1] = list[index1 - 1];
list[index1 - 1] = temp;
}
}
}
然后在Code中你可以:
List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
Console.WriteLine("Original List");
foreach (int i in list)
{
Console.Write(i + ",");
}
Console.WriteLine(Environment.NewLine + "Move Index 2 Down");
list.Move(2);
foreach (int i in list)
{
Console.Write(i + ",");
}
Console.WriteLine(Environment.NewLine + "Move Index 3 Up");
list.Move(3, false);
foreach (int i in list)
{
Console.Write(i + ",");
}
输出将是:
Original List
1,2,3,4,5,6,7,
Move Index 2 Down
1,2,4,3,5,6,7,
Move Index 3 Up
1,2,3,4,5,6,7,