3
votes

I am trying to list all combobox items in one messagebox. but all i get is every item comes up in its own messagebox. I know the messagebox needs to be outside the loop but when i do that it says the variable is unassigned. Any help would be great.

private void displayYachtTypesToolStripMenuItem_Click(object sender, EventArgs e) {

       string yachtTypesString;

        for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)

        {
            yachtTypesString=typeComboBox.Items[indexInteger].ToString();
            MessageBox.Show(yachtTypesString);
        }

       }
4
The problem is you need to assing string yachtTypesString; to a value in your case a empty string string yachtTypesString = ""; and it will workVajura

4 Answers

3
votes

Do it like this,

    StringBuilder yachtTypesString = new StringBuilder();
    for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
    {
        yachtTypesString.AppendLine(typeComboBox.Items[indexInteger].ToString());
    }
    MessageBox.Show(yachtTypesString.ToString());

NOTE: Do not do string concatenation with a string, use StringBuilder object as doing it in a string creates a new instance.

1
votes

You can try using Linq:

  MessageBox.Show(String.Join(Environment.NewLine, typeComboBox.Items.Cast<String>()));

and let it do all the work for you

0
votes

Try this

            string yachtTypesString="";

    for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)

    {
        yachtTypesString=yachtTypesString +  typeComboBox.Items[indexInteger].ToString();

    }

     MessageBox.Show(yachtTypesString);
0
votes

list all combobox items in one messagebox

Please play with Below code To Get Combobox all Text

private void Form1_Load(object sender, EventArgs e) { DataTable dtcheck = new DataTable(); dtcheck.Columns.Add("ID"); dtcheck.Columns.Add("Name"); for (int i = 0; i <= 15; i++) { dtcheck.Rows.Add(i, "A" + i); }

        comboBox1.ValueMember = "ID";
        comboBox1.DisplayMember = "Name";
        comboBox1.DataSource = dtcheck;


    }
}

    private void button1_Click(object sender, EventArgs e)
    {

        string MessageText = string.Empty;

        foreach(object item in comboBox1.Items)
        {
           DataRowView row = item as DataRowView;

           MessageText += row["Name"].ToString() + "\n";
        }

        MessageBox.Show(MessageText, "ListItems", MessageBoxButtons.OK,MessageBoxIcon.Information);
    }