GuGri
GuGri

Reputation: 13

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());
//Here comes the FormatException
             }

            int count = listBox1.Items.Count;
            double average = sum / count;
            lbcount.Text = count.ToString();
            lbsum.Text = sum.ToString();
            lbavg.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 obviously 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.

Upvotes: 1

Views: 459

Answers (1)

LarsTech
LarsTech

Reputation: 81610

You are getting that error because your object's ToString function is returning the string "DataRowView", which is not a number you can use. A cast is required:

sum += Convert.ToDouble(((DataRowView)item)["Frage-Nr"]);

It probably makes more sense to work with the data source directly, in which case, you can try this:

foreach (DataRow dr in ((DataTable)itemWerteBindingSource.DataSource).Rows) 
{
  sum += Convert.ToDouble(dr["Frage-Nr"]);
}

Upvotes: 1

Related Questions