我有两个listBoxes。第一个列表框包含流量违规列表。当您单击添加按钮并执行代码时,listbox2获得此项“ListBoxTest.Violation”,而不是listBox1中显示的项目......
我的代码出了什么问题?
namespace ListBoxTest
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
private List<Violation> violationList = new List<Violation>();
public MainForm()
{
InitializeComponent();
}
void MainFormLoad(object sender, EventArgs e)
{
LoadViolations(); // Initialize and add violations to violationList.
listBox1.DataSource = violationList; // Set the DataSource property.
listBox1.ValueMember = "Code";
listBox1.DisplayMember = "Description";
}
void LoadViolations()
{
Violation violation;
violation = new Violation("001", "Beating the red light");
violationList.Add(violation);
violation = new Violation("002", "Exceeding posted speed limit on the road");
violationList.Add(violation);
violation = new Violation("003", "Driving a vehicle without license to drive");
violationList.Add(violation);
violation = new Violation("004", "Driving a non registered vehicle");
violationList.Add(violation);
violation = new Violation("005", "Vehicle has no plate number");
violationList.Add(violation);
}
void BtnAddClick(object sender, EventArgs e)
{
listBox2.Items.Add(listBox1.SelectedItem); // Add item from listBox1 to listBox2;
}
}
/// <summary>
/// Violation Class
/// Properties: Code, Description
/// </summary>
public class Violation
{
private string _code;
private string _description;
public Violation(string code, string description)
{
_code = code;
_description = description;
}
public String Code
{
get { return _code; }
set { _code = value; }
}
public String Description
{
get { return _description; }
set { _description = value; }
}
}
}
答案 0 :(得分:0)
键入将所选项目强制转换为违规。这应该可以解决问题。 编辑:我已修改代码以解决问题。
private void AddClick(object sender, EventArgs e)
{
// Set the DataSource property.
listBox2.ValueMember = "Code";
listBox2.DisplayMember = "Description";
listBox2.Items.Add((Violation)listBox1.SelectedItem);
}
答案 1 :(得分:0)
确保listbox2
与listbox1
具有相同的设置,例如listbox2.ValueMember
,listbox2.DisplayMember
..