Sully
Sully

Reputation: 3

Populate TextBoxes from a List

I am trying to populate TextBoxes from a list. I have been able to populate ComboBoxes with 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);
    }
}

But when I try and apply the same principle to TextBoxes

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);
    }
}

TextBox does not like Items.Add ( aosList[n]Items.Add(id); ) I am looking fore a reference or guidance resolving this issue. Thanks!

Upvotes: 0

Views: 518

Answers (3)

Slai
Slai

Reputation: 22876

int i = 1;
foreach (var asset in assets)
{
    this.Controls["txtAsset" + i].Text = asset.ID;
    i++;
}   

Upvotes: 0

Zaid Mirza
Zaid Mirza

Reputation: 3699

You should use ComboBox for your problem,instead of iterating on each element,You simply use below lines to populate combobox.

comboList.DataSource=assets;
comboList.DisplayMember="ID";
comboList.ValueMember="ID";

However,if you want your values in TextBox,you can use TextBox.AppendText Method, but it will not work like ComboBox as it will contain texts+texts+texts, will not have indexes like 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");
    }
}

Upvotes: 2

Arctic Vowel
Arctic Vowel

Reputation: 1522

A Combobox is a collection of items, and so has an Items property from which you can add/remove to change it's contents. A Textbox is just a control that displays some text value, so it has a Text property which you can set/get, and which denotes the string that is displayed.

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!
}

Upvotes: 0

Related Questions