C# 按名称检索文本框
在我的项目中,我知道动态生成的C# 按名称检索文本框,c#,winforms,dynamic,textbox,C#,Winforms,Dynamic,Textbox,在我的项目中,我知道动态生成的TextBox的名称。是否有任何解决方案可以从其他方法检索此TextBox文本。从另一个意义上说,我希望按名称获取TextBox,并希望在代码的其他部分中使用。 我有TextBox这样的分配 private void Met(string rowNo) { TextBox t2 = new TextBox(); t2.Name = "itemAmt" + rowNo; PurchaseItemEntryDyPanel.Controls.Add
TextBox
的名称。是否有任何解决方案可以从其他方法检索此TextBox
文本。从另一个意义上说,我希望按名称获取TextBox
,并希望在代码的其他部分中使用。
我有TextBox
这样的分配
private void Met(string rowNo)
{
TextBox t2 = new TextBox();
t2.Name = "itemAmt" + rowNo;
PurchaseItemEntryDyPanel.Controls.Add(t2);
}
除了用名字还有别的方法吗?有什么解决方案吗?您可以从表单集合中获取
文本框,其名称如下:
var myTextBox = this.Controls[textBoxName];
您可以通过以下名称从表单集合中获取文本框
:
var myTextBox = this.Controls[textBoxName];
您没有显示太多的代码,但我假设您正在将其添加到表单上的控件集合中。否则,当方法结束时,在Met
中创建的TextBox
将超出范围,就像任何其他局部变量一样
private void Met(string rowNo)
{
TextBox t2 = new TextBox();
t2.Name = "itemAmt" + rowNo;
this.Controls.Add(t2); // need to add the TextBox to your form's controls
}
然后,您可以使用Selman22的解决方案,或者,如果控件可能被添加到组框
或面板
,您也需要搜索所有子控件:
var myControl = this.Controls.Find("itemAmt4", true);
if (myControl != null)
myControl.Enabled = true;
您没有显示太多的代码,但我假设您正在将其添加到表单上的控件集合中。否则,当方法结束时,在Met
中创建的TextBox
将超出范围,就像任何其他局部变量一样
private void Met(string rowNo)
{
TextBox t2 = new TextBox();
t2.Name = "itemAmt" + rowNo;
this.Controls.Add(t2); // need to add the TextBox to your form's controls
}
然后,您可以使用Selman22的解决方案,或者,如果控件可能被添加到组框
或面板
,您也需要搜索所有子控件:
var myControl = this.Controls.Find("itemAmt4", true);
if (myControl != null)
myControl.Enabled = true;
当我想从表单中读取发布的数据时,我个人会使用name
当控件应该是唯一的时,我会使用Id
。所以代码有点不同:
var t2 = new TextBox();
t2.ID = "itemAmt" + rowNo;
//since you mention in the comments, add it to the panel
yourPanel.Controls.Add(t2);
然后获取文本框值
var controlId = "itemAmt" + rowNo;
var t2 = ((TextBox)(yourPanel.FindControl(controlId)));
if(t2 != null)
{
//do someting
//t2.Text = "something";
//t2.Enabled = true;
}
如果您不愿意进行更改,请查看之前发布的解决方案。当我想从表单中读取发布的数据时,我个人会使用名称
当控件应该是唯一的时,我会使用Id
。所以代码有点不同:
var t2 = new TextBox();
t2.ID = "itemAmt" + rowNo;
//since you mention in the comments, add it to the panel
yourPanel.Controls.Add(t2);
然后获取文本框值
var controlId = "itemAmt" + rowNo;
var t2 = ((TextBox)(yourPanel.FindControl(controlId)));
if(t2 != null)
{
//do someting
//t2.Text = "something";
//t2.Enabled = true;
}
如果您不愿意进行更改,请查看前面发布的解决方案。在课堂上使用:
foreach (Control tempCtrl in this.Controls)
{
// Determine he control is textBox1,
if (tempCtrl.Name == "itemAmt" + rowNo)
{
this.Controls.Remove(tempCtrl);
}
}
在课堂上使用此选项:
foreach (Control tempCtrl in this.Controls)
{
// Determine he control is textBox1,
if (tempCtrl.Name == "itemAmt" + rowNo)
{
this.Controls.Remove(tempCtrl);
}
}
哪个框架?wpf?winform?哪个框架?wpf?winform?@AskThakare,在注释中的代码段中,您从未将控件添加到面板或当前容器(此),因此它不在控件集合中。创建新小部件不会自动将其添加到控件集合。@AskThakare,在注释中的代码段中,您从未将控件添加到面板或当前容器(此),因此它不在控件集合中。创建新小部件不会自动将其添加到控件集合。