Reputation: 387
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);
}
}
Upvotes: 3
Views: 2756
Reputation: 1
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);
}
Upvotes: 0
Reputation: 186668
You can try using Linq:
MessageBox.Show(String.Join(Environment.NewLine, typeComboBox.Items.Cast<String>()));
and let it do all the work for you
Upvotes: 1
Reputation: 1967
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.
Upvotes: 3
Reputation: 812
Try this
string yachtTypesString="";
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString=yachtTypesString + typeComboBox.Items[indexInteger].ToString();
}
MessageBox.Show(yachtTypesString);
Upvotes: 0