c# - 努力添加到 ListBox
问题描述
所以我正在为我在大学的作业制作这个小程序,我发现很难在我的表格中添加到我的列表中。这是我的代码:
public partial class WorkOutBeam : Form
{
Check checkLib;
public BindingList<ListBox> list;
public WorkOutBeam()
{
InitializeComponent();
}
public void StartForm(object sender, EventArgs e)
{
list = new BindingList<ListBox>();
listBox1.DataSource = list;
}
private void NewForce_Click(object sender, EventArgs e)
{
NewForceName forceItem = new NewForceName();
forceItem.Show();
}
public void AddToForceList(string name)
{
list.Items.Add(name);
}
}
下面的 NewForceName 类:
public partial class NewForceName : Form
{
public WorkOutBeam workOutBeam;
public NewForceName()
{
InitializeComponent();
}
private void OkButton_Click(object sender, EventArgs e)
{
if (NewForceNames.Text != "")
{
ReferToLibs();
workOutBeam.AddToForceList(NewForceNames.Text);
Close();
}
}
private void ReferToLibs()
{
workOutBeam = new WorkOutBeam();
}
private void NewForceName_Load(object sender, EventArgs e)
{
}
}
所以我对我的程序说,“给我一个新的力量”。当它这样做时,它会初始化一种新形式的“NewForceName”。我在一个文本框中输入并单击“确定”,这将启动一个公共方法,如下所示:
该列表是一个绑定列表,它将列表框作为数据源。但是该程序告诉我,由于受保护,Items 部分无法访问,但我不知道如何将其添加为公共。我尝试查看我的 listBox 的属性,但无济于事。
解决方案
试一试:
public partial class WorkOutBeam : Form
{
Check checkLib;
// public BindingList<ListBox> list; // get rid of this for now
public WorkOutBeam()
{
InitializeComponent();
}
/*public void StartForm(object sender, EventArgs e)
{
list = new BindingList<ListBox>();
listBox1.DataSource = list;
}*/
private void NewForce_Click(object sender, EventArgs e)
{
NewForceName forceItem = new NewForceName(this); // pass a reference to this
// instance of WorkoutBeam
forceItem.Show();
}
public void AddToForceList(string name)
{
// we should do some more things here, but let's keep it simple for now
listBox1.Items.Add(name);
}
}
和
public partial class NewForceName : Form
{
public WorkOutBeam workOutBeam;
public NewForceName( WorkoutBeam beam ) // we take a WorkoutBeam instance as CTOR param!
{
InitializeComponent();
workoutBeam = beam;
}
private void OkButton_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(NewForceNames.Text))
{
workOutBeam.AddToForceList(NewForceNames.Text);
Close();
}
}
// DO NOT create new WorkoutBeams every time. Use the original.
/*private void ReferToLibs()
{
workOutBeam = new WorkOutBeam();
}*/
}
免责声明:我没有解决此代码中的每一个问题。这足以让它按预期“工作”。
推荐阅读
- python - python setup.py sdist bdist_wheel 的输出目录
- matlab - 在 MATLAB 中查找函数的最小值和最大值
- php - 带有帖子的容器,使用 MySQL 和 PHP - 单击右箭头更改文章
- android - Android 应用程序在启动时关闭。给出错误'原因:仅执行(无读取)内存访问错误;可能是由于 .text' 中的数据
- java - 缺少 While 循环逻辑
- visual-studio-code - VS Code 仅显示 1 行可能的导入路径。如何将其转换回默认列表框?
- sql - 无法在 SQL Server 的现有列中分配默认约束
- performance - Chrome API 功能阻止渲染,直到应用所有更改
- mongodb - 如何触发猫鼬updateAt
- c# - 当我使用计时器时 UI 阻塞