lundi 23 février 2015

Calculating Items of a listbox which has a Databinding

I have a listbox1 (in C# winforms) which is FilledBy a DataBindingSource (its a sqlite.db).



//
// listBox1
//
this.listBox1.DataSource = this.itemWerteBindingSource;
this.listBox1.DisplayMember = "Frage-Nr";
this.listBox1.FormatString = "N0";
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(12, 12);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(113, 225);
this.listBox1.TabIndex = 15;


The Form_Load event is:



private void Form_Load(object sender, EventArgs e)
{
this.item_WerteTableAdapter.Fill(this.erhebungenDataSet.Item_Werte);
}


Being compiled the (Items/Values) Numbers (1 2 3) of the Data row are shown correctly in listbox1


The Button_Click event for showing the results in labels is:



private void btnresultB1_Click(object sender, EventArgs e)
{
if (listBox1.Items.Count == 0)
{
MessageBox.Show("There are no items in the listbox");
return;
}

double sum = 0;

foreach (object item in listBox1.Items)
{
sum += Convert.ToDouble(item.ToString());
}

int count = listBox1.Items.Count;
double average = sum / count;
lbcountLB2.Text = count.ToString();
lbsumLB2.Text = sum.ToString();
lbavgLB2.Text = average.ToString();
}


The Items of the listbox1 are count but not calculated - Format Exception. When I send the Data to another listbox2



foreach (var item in listBox1.Items)
{
listBox2.Items.Add(item);
}


listbox2 doesnt show the Data (1 2 3), but "System.Data.DataRowView". So, I have a Problem with the Values of the Items in listbox1 which can´t be interpreted / converted. I tried it with decimal instead of double - same Format Exception.


I dont want to let the db (sqlite) do the calculation.


I´m rather new in programming. How can I calculate such a data bound listbox? Conversion to generic list doesn´t work also. If put some Numbers into listbox2 and change the button event to listbox2 everything works fine. I found no answers in days of searching and trying. Many Thanks in advance.


Aucun commentaire:

Enregistrer un commentaire