ListBox
listBox1.Items.Clear(); //ListBox löschen
Speichern
if(saveFileDialog1.ShowDialog()==DialogResult.OK)
{
File.WriteAllLines(saveFileDialog1.FileName,listBox1.Items.Cast<string>());
}
Öffnen
if(openFileDialog1.ShowDialog()==DialogResult.OK)
{
listBox1.Items.Clear();
string[] lines;
lines = File.ReadAllLines(openFileDialog1.FileName);
foreach(string line in lines)
{
listBox1.Items.Add(line);
}
}
Text übernehmen
if(textBox1.Text!="")
{
listBox1.Items.Add(textBox1.Text);
textBox1.Text = "";
textBox1.Focus();
}
Ganze Liste löschen
listBox1.Items.Clear();
textBox1.Focus();
Ausgewählten Text löschen
if (listBox1.SelectedIndex != -1)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
else
{
MessageBox.Show("Bitte ein Element in der ListBox auswählen!");
}
/* Variante 2
Console.WriteLine(listBox1.SelectedIndex);
try
{
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
catch
{
MessageBox.Show("Bitte Eintrag auswählen!");
} */
Element ausgeben
if(listBox1.SelectedIndex!=-1)
MessageBox.Show(listBox1.SelectedItem.ToString());
else
MessageBox.Show("Bitte ein Element auswählen!");
Anzahl der Elemente
MessageBox.Show("Es sind insgesamt " + listBox1.Items.Count.ToString() + " Elemente vorhanden!");
Summe aller Elemente
try
{
int summe = 0;
for (int i = 0; i < listBox1.Items.Count; i++)
{
summe = summe + int.Parse(listBox1.Items[i].ToString());
}
MessageBox.Show("Die Summe aller Zahlen beträgt: " + summe.ToString());
}
catch
{
MessageBox.Show("Sie haben eventuell keine Zahlen eingegeben!");
}