【发布时间】:2017-07-07 09:07:34
【问题描述】:
我的情况:
我在Form1 上有一个填充的checklistbox 控件。
然后我在Form2 上有一个listView 控件。
我希望用户能够在Form1 上检查checklistbox 上的项目,然后单击Form1 上的按钮打开Form2。
Form2 包含listView 控件,我想用仅来自checklistbox 的Form1 上的选中项填充该控件。
我试过了
namespace Boodschappenlijst
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string[] strKruideniersw = new string[] { Boodschappenlijst.producten[0], Boodschappenlijst.producten[1], Boodschappenlijst.producten[2] };
public static string[] strVerswaren = new string[] { Boodschappenlijst.producten[3], Boodschappenlijst.producten[4], Boodschappenlijst.producten[5] };
public static string[] strVerzorgingspr = new string[] { Boodschappenlijst.producten[6], Boodschappenlijst.producten[7], Boodschappenlijst.producten[8], Boodschappenlijst.producten[9] };
public static List<string> kruidenierswList = new List<string>(strKruideniersw);
public static List<string> verswarenList = new List<string>(strVerswaren);
public static List<string> verzproductenList = new List<string>(strVerzorgingspr);
public static string[] strKruidenierswCh;
public void Form1_Load(object sender, EventArgs e)
{
clbKruidenierswaren.Items.AddRange(strKruideniersw);
clbVerswaren.Items.AddRange(strVerswaren);
clbVerzproducten.Items.AddRange(strVerzorgingspr);
strKruidenierswCh = clbKruidenierswaren.CheckedItems;
}
// TODO
// public string kruidenierswChecked = clbKruidenierswaren.CheckedItems;
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 form2 = new Form2();
// Show the settings form
form2.Show();
}
}
public abstract class Boodschappenlijst : Form1
{
public static string[] producten = new string[] { "Peper", "Zout", "Kruidnagel", "Sla", "Komkommer", "Tomaten", "Tandpasta", "Shampoo", "Wax", "Deodorant" };
// Not working.. clbKruidenierswaren is not static.
List<string> items = clbKruidenierswaren.CheckedItems.Cast<string>().ToList();
// Make form1 controls accessible for other classes?
// Form1 form1 = Application.OpenForms.OfType<Form1>().FirstOrDefault();
}
}
但是我得到了错误
字段初始值设定项不能引用非静态字段、方法或属性“Form1.clbKruidenierswaren”。
您能指导我找到一个可行的解决方案吗?
【问题讨论】:
-
不要将
checkboxlist传递给ctor,而是传递所选ID 的列表,而不是像List<int>。然后根据 id 而不是复选框填充您的ListView。如果您想在创建时将数据传递给Form,请创建一个继承Form的BaseForm类,然后放置一个类似object InitialisationData {get;set;}的属性。 -
@Dan Rayson:你能给我举个例子吗?老实说,这对我来说还没有多大意义..
-
Hoi Richard ;),我看到的是你以多种方式填充你的列表,它背后的想法是你正在学习还是你实际上正在实施这个?因为有些东西可能需要大修..
-
Hoi Blaatz0r,嗯,我是 C# 新手,并且正在学习。如果我的代码对您没有意义,请评论它,并告诉我我需要更改哪些内容才能使其正常工作。 :)
-
@RichardPostma 我可以看出你是荷兰人:P 为什么类是抽象的?
标签: c# winforms listview checkeditems