GroupBox.Controls.count在C#中不更新
本文关键字:更新 Controls count GroupBox | 更新日期: 2023-09-27 18:00:07
我正在尝试搜索一系列联系人。(保存在一个xml文件中,然后恢复到变量myContacts)搜索代码很好,它得到了正确的结果,我的问题是在文本框中显示联系人。这是我在文本框中显示结果的代码:
private void showContact(int index)
{
txtNameResult.Text = myContacts[index].getName();
txtFNameResult.Text = myContacts[index].getFName();
txtNumberResult1.Text = myContacts[index].getSingleNumber(0);
int position = 30;
for (int i = 1; i < myContacts[index].getNumCount(); i++)
{
TextBox formtxtBox = txtNumberResult1;
TextBox txtMyNum = new TextBox();
gbResult.Controls.Add(txtMyNum);
txtMyNum.Size = formtxtBox.Size;
txtMyNum.Location = new Point(formtxtBox.Location.X, formtxtBox.Location.Y + position);
position += 30;
txtMyNum.Text = myContacts[index].getSingleNumber(i);
txtMyNum.ReadOnly = true;
txtMyNum.Name = "txtNumberResult" + (i + 1).ToString();
txtMyNum.TabIndex = i + 2;
if (this.Height < 414)
{
gbResult.Height += 30;
this.Height += 30;
}
}//end of for
}//end of show contact
这是我的表格:
[搜索表格][1]
每个联系人最多可以有5个号码,每个额外的号码都会在txtNumberResult1下添加一个文本框,并扩展组框和表单高度。问题是,当我搜索一个有5个号码的联系人时,它会正确显示,但如果我在那之后搜索另一个联系人,额外的文本框不会删除。这很奇怪,但经过一个小时的调试,我终于发现问题出在我的clearResults()
代码中——gbResult.Controls.count
(gbResult是groupbox)是8(现在应该是11)这是我的clearResults()
代码(在Save按钮点击事件开始时执行的代码,它重置了所有内容):
private void clearResults()
{
gbResult.Focus();
txtNameResult.Text = "";
txtFNameResult.Text = "";
txtNumberResult1.Text = "";
foreach (Control txtBox in gbResult.Controls)
{
if (txtBox.GetType() == typeof(TextBox))
{
if (txtBox.Name != "txtNumberResult1" && txtBox.Name != "txtNameResult" && txtBox.Name != "txtFNameResult")
{
//remove the controls
txtBox.Text = "";
gbResult.Controls.Remove(txtBox);
txtBox.Dispose();
}//end of if
}//end of if
}//end of foreach
//shrink the form
while (this.Height > 294 && gbResult.Height > 129)
{
this.Height -= 30;
gbResult.Height -= 30;
}
}//end of clear results
提前谢谢你,如果这看起来有点令人困惑,我很抱歉!PS:我无法发布图片,因为我没有所需的代表:|
编辑:这是正确的clearResults()方法:
private void clearResults()
{
gbResult.Focus();
txtNameResult.Text = "";
txtFNameResult.Text = "";
txtNumberResult1.Text = "";
//foreach (Control txtBox in gbResult.Controls)
for (int i = 15; i > -1; i--)
{
try
{
var txtBox = gbResult.Controls[i];
if (txtBox.GetType() == typeof(TextBox))
{
if (txtBox.Name != "txtNumberResult1" && txtBox.Name != "txtNameResult" && txtBox.Name != "txtFNameResult")
{
//remove the controls
txtBox.Text = "";
gbResult.Controls.Remove(txtBox);
txtBox.Dispose();
}//end of if
}//end of if
}//end of try
catch (Exception)
{
continue;
}
}//end of for
//shrink the form
while (this.Height > 294 && gbResult.Height > 129)
{
this.Height -= 30;
gbResult.Height -= 30;
}
}//end of clear results
对于那些有同样问题的人:)
在clearResult()
方法中,尝试按相反顺序删除控件:
for (int i = 20; i > -1; i--)