【发布时间】:2015-11-17 07:16:22
【问题描述】:
当我检查 CheckBoxList Items 时,会添加动态 texbox。但是在未选中时,我想删除特定的文本框。该代码在添加文本框时运行良好,但在删除时给了我例外。任何帮助都会很棒。
我的代码:
iy = 0;
private void checkedListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (load == false)
{
return;
}
PackingDetails pd = new PackingDetails();
var txt = new TextBox();
for (iy = 0; iy < checkedListBox1.Items.Count; iy++)
if (checkedListBox1.GetItemChecked(iy))
{
txt.Name = iy.ToString();
txt.Text = iy.ToString();
txt.Location = new Point(23, 32 + (iy * 28));
txt.Visible = true;
this.Controls.Add(txt);
break;
}
else if (checkedListBox1.GetItemCheckState(iy) == CheckState.Unchecked)
{
foreach (TextBox t in this.Controls)
{
if (t.Name == iy.ToString())
// 如果条件是最上面的文本框而不是点击的文本框被删除,我跳过这里。
{
this.Controls.Remove(t);
t.Dispose();
break;
}
}
break;
}
}
或
我也试过了
int iy = 0;
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
TextBox txt = new TextBox();
panel1.VerticalScroll.Value = VerticalScroll.Minimum;
if (e.NewValue == CheckState.Checked)
{
txt.Name = iy.ToString();
txt.Text = iy.ToString();
txt.Location = new Point(23, 32 + (iy * 28));
txt.Visible = true;
this.Controls.Add(txt);
count = iy;
iy++;
}
else
{
foreach (Control control in this.Controls)
{
if (control is TextBox)
{
// here it deletes the topmost textbox but not the clicked one. Here if I used if condition like control.Name == iy.ToString() Nothing happens
this.Controls.Remove(control);
control.Dispose();
break;
}
}
}
}
【问题讨论】:
-
请提供具体的异常信息。
-
无效的 CastException 详细信息无法将“System.Windows.Forms.CheckedListBox”类型的对象转换为“System.Windows.Forms.TextBox”类型。
-
这个错误发生在哪里?
-
@manraj 不要对我们发号施令。我们在这里试图免费为您提供帮助。实际上,我们需要时间来提供帮助,因此您至少可以对社区友好。
-
我已经更新了这个问题。它也不适用于checkedListBox1_ItemCheck。
标签: c# .net winforms checkboxlist