从列表中填充文本框
本文关键字:文本 填充 列表 | 更新日期: 2023-09-27 18:02:56
我试图从列表填充文本框。我已经能够用comboList:
填充组合框了var comboList = new System.Windows.Forms.ComboBox[4];
comboList[0] = cmbSite1Asset;
comboList[1] = cmbSite2Asset;
comboList[2] = cmbSite3Asset;
comboList[3] = cmbSite4Asset;
List<CRCS.CAsset> assets = _rcs.Assets;
foreach (CRCS.CAsset asset in assets)
{
string id = asset.ID;
for (int i = 0; i < 4; ++i)
{
comboList[i].Items.Add(id);
}
}
但是当我尝试将相同的原则应用于文本框
时var aosList = new System.Windows.Forms.TextBox[8];
aosList[0] = txtAsset1;
aosList[1] = txtAsset2;
aosList[2] = txtAsset3;
aosList[3] = txtAsset4;
aosList[4] = txtAsset5;
aosList[5] = txtAsset6;
aosList[6] = txtAsset7;
aosList[7] = txtAsset8;
foreach (CRCS.CAsset asset in assets)
{
string id = asset.ID;
for (int n = 0; n < 8; ++n)
{
aosList[n].Items.Add(id);
}
}
文本框不喜欢项。Add(aosList[n]Items.Add(id);)我正在寻找解决这个问题的参考或指导。谢谢!
您应该使用ComboBox来解决您的问题,而不是在每个元素上迭代,您只需使用下面的行来填充ComboBox。
comboList.DataSource=assets;
comboList.DisplayMember="ID";
comboList.ValueMember="ID";
然而,如果你想要你的值在TextBox
,你可以使用TextBox.AppendText
方法,但它不会像ComboBox
一样工作,因为它将包含文本+文本+文本,不会有索引像ComboBox.
private void AppendTextBoxLine(string myStr)
{
if (textBox1.Text.Length > 0)
{
textBox1.AppendText(Environment.NewLine);
}
textBox1.AppendText(myStr);
}
private void TestMethod()
{
for (int i = 0; i < 2; i++)
{
AppendTextBoxLine("Some text");
}
}
一个组合框是一个项目的集合,因此有一个Items
属性,您可以从中添加/删除来改变它的内容。一个文本框只是一个控件,显示一些文本值,所以它有一个Text
属性,你可以设置/获取,它表示显示的字符串。
System.Windows.Forms.TextBox[] aosList = new System.Windows.Forms.TextBox[8];
aosList[0] = txtAsset1;
aosList[1] = txtAsset2;
aosList[2] = txtAsset3;
aosList[3] = txtAsset4;
aosList[4] = txtAsset5;
aosList[5] = txtAsset6;
aosList[6] = txtAsset7;
aosList[7] = txtAsset8;
for (int n = 0; n < 8; ++n)
{
aosList[n].Text = assets[n].ID; // make sure you have 8 assets also!
}
int i = 1;
foreach (var asset in assets)
{
this.Controls["txtAsset" + i].Text = asset.ID;
i++;
}