我的Windows C#WinForms应用程序中有2个列表框。我已经编写了代码来在我的2个列表框之间移动项目。我可以选择任意/多个项目并在框之间移动它们。但是,如果我选择列表框中的底部项目并将其移动到另一个列表框,则表格中移动的内容显示不正确。它没有显示实际内容,而是显示: - 我移动的条目上方的每个条目的ProgramName __。objectname!这只发生在列表框中的最后一项。如果我选择显示错误的条目并将其移至其他列表框,则会显示正确的信息。
在我看来这是一个错误,但我不确定。我可以移动列表框中的任何其他项目,两个列表框都会正确显示。
public class customers
{
public int id { get; set; }
public string name {get; set; }
}
this.table1Box.DataSource = this.customersBindingSource;
this.table1Box.DisplayMember = "name";
this.table1Box.Name = "Table1Name";
this.table1Box.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.table1Box.Sorted = true;
this.table1Box.TabIndex = 13;
this.table1Box.ValueMember = "id";
this.table2Box.DataSource = this.customersBindingSource;
this.table2Box.DisplayMember = "name";
this.table2Box.Name = "Table2Name";
this.table2Box.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.table2Box.Sorted = true;
this.table2Box.TabIndex = 14;
this.table2Box.ValueMember = "id";
// Click method for moving table 1 -> table 2
private void table1ToTable2Button_Click(object sender, EventArgs e)
{
foreach (int i in this.table1Box.SelectedIndices)
{
selectedCustomer = (customers)this.table1Box.Items[i];
table2List.Add(selectedCustomer);
table1List.Remove(selectedCustomer);
}
this.table1Box.DataSource = this.emptyList;
this.table1Box.DataSource = this.table1List;
this.table1Box.Update();
this.table2Box.DataSource = this.emptyList;
this.table2Box.DataSource = this.table2List;
this.table2Box.Update();
}
![计划开始时的图片] http://www.mclenaghan.com/Pic1.jpg
![移动最后一项后的图片] http://www.mclenaghan.com/Pic2.jpg
![图片移动项目2] http://www.mclenaghan.com/Pic3.jpg
答案 0 :(得分:1)
确保您绑定到BindingList<customers>
。
您不需要将DataSource
设置为空列表,然后再次设置为实际列表,然后调用ListBox.Update()
。这似乎有效,但这也意味着你在绑定中做错了。
还有一件事 - 不要手动编辑设计器生成的代码,使用属性窗格。我发现即使我在InitializeComponent
方法中更改了代码序列,列表框也会显示不正确。
BindingList<customers> table1List;
BindingList<customers> table2List;
public FormWith2Listboxes()
{
InitializeComponent();
table1List = new BindingList<customers>();
table1List.Add(new customers() { id = 1, name = "name1" });
table1List.Add(new customers() { id = 2, name = "name2" });
table1List.Add(new customers() { id = 3, name = "name3" });
table2List = new BindingList<customers>();
table2List.Add(new customers() { id = 4, name = "name4" });
this.table1Box.DataSource = this.table1List;
this.table2Box.DataSource = this.table2List;
}
private void table1ToTable2Button_Click(object sender, EventArgs e)
{
foreach (int i in this.table1Box.SelectedIndices)
{
var selectedCustomer = (customers)this.table1Box.Items[i];
table2List.Add(selectedCustomer);
table1List.Remove(selectedCustomer);
}
}