简体   繁体   中英

Problem with format in C# with DataGridView and TextBox

I have a problem with format in C#. I have a DataGridView and a TextBox. In this datagridview, there is a column: the single price (format int). I want sum every elements of single price's column and insert the result into this textbox, but Visual Studio gives me a problem with format of string input ("Format of input's string is not correct"). this is the code than i used:

int TOT = 0;
                for (int i = 0; i < dataGridView3.Rows.Count; i++)
                {
                    TOT = TOT + Convert.ToInt32(dataGridView3.Rows[i].Cells[6].ToString());
                }
                textBoxTot.Text = Convert.ToString(TOT);

Can you help me with this bad error?

UPDATE: I think that the problem now is another. I can't find the methods of MySql.Data.MySqlClient library that it can give me the result of query.

MySqlCommand command = new MySqlCommand();
            String sumQuery = "SELECT SUM(`prezzo`) FROM `fatturetemp`";
            command.CommandText = sumQuery;
            command.Connection = conn.getConnection();
            command.Parameters.Add("@prezzo", MySqlDbType.Int32).Value = costo;
            conn.openConnection();
            conn.closeConnection();

How is the command that give me the result of sumQuery. If i find this command, i can take the result of query and paste in textbox

It is weird that you are first converting to a string and then to an int.

int TOT = 0;
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
    if (!dataGridView3.Rows[i].IsNewRow &&
  int.TryParse(dataGridView3.Rows[i].Cells[6].Value.ToString(), out int v))
       TOT += v;
}
textBoxTot.Text = TOT.ToString();

EDIT: Edited for your updated question. You shouldn't ask question inside a question buy anyway:

string sumQuery = "SELECT SUM(`prezzo`) FROM `fatturetemp`";
decimal total = 0M;
using (MySqlConnection cn = new MySqlConnection(" your connection string here "))
using (MySqlCommand cmd = new MySqlCommand(sumQuery, cn))
{
  cn.Open();
  total = Convert.ToDecimal(cmd.ExecuteScalar());
  cn.Close();
}
Console.WriteLine(total);

If your datagridview is showing a datatable (Ie your data is stored in a datatable) you can add a DataColumn to the datatable whose .Expression property is set to the string "SUM([Price])" , where Price is the name of your numeric datatyped column holding the price info.

Now every row in the table will have the sum of the prices (the same value over and over again), so if you want to databind your textBox to this new column then it will always show the sum no matter which row is the current row (because all rows have the same value). It will also auto update without you having to do anything!

And if you're not using databinding to a datatable, I recommend that you do do it, because it represents good MVC practice of keeping your data in one thing (DataTable) and showing it in another (DataGridView) and keeping these concerns separate

It would look something like this, as a quick example:

        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Price", typeof(int));
        dt.Columns.Add("CalculatedTotal", typeof(int)).Expression = "SUM([Price])";
        dt.Rows.Add("Apples", 100);
        dt.Rows.Add("Oranges", 200);

        BindingSource bs = new BindingSource();
        bs.DataSource = dt;

        WhateverDataGridView.DataSource = bs;
        totalTextBox.DataBindings.Add(new Binding("Text", bs, "CalculatedTotal", true));

Here we have a data model (the datatable) where we keep our data. It has a couple of things we can set directly, and an third column that calculates based on the existing prices in all the table. If you look at this in the datagridview (assuming you have autogeneratecolumns turned on) you'll see that both rows have 300 for the CalculatedTotal , but they have individual amounts for price. There is a device called a BindingSource that sits between the datatable and the UI controls; you don't have to have one but it makes certain things easier regards updating controls when the data changes, and it maintains a concept of "current" - essentially whatever the current row is you're looking at in the datagridview; it all helps to avoid having to ask the DGV for anything - we just let the user type into the DGV, and it shows the data out of the datatable. All our dealings can be with the datatable directly - if you wrote a button to loop through the table and double all the prices, the controls in the UI would just reflect the change automatically. The textbox is connected to the CalculatedValue column via databinding; whatever the current row is, the textbox will show the CalculatedValue . Because the CalculatedValue column has the same value on every row, and they always all update if any price changes, the total textbox will always show the total. Add another textbox bound to Name to see what I mean; as you click around the grid and select different rows to be the "Current" row, the Name will change but the total does not. In truth it is actually changing in the same way that Name is, it's just that because the actual numeric value is the same on every row the contents of the textbox look like they don't change

UPDATE: I think that the problem now is another. I can't find the methods of MySql.Data.MySqlClient library that it can give me the result of query.

public string sommaFattura(String costo)
        {
    MySqlCommand command = new MySqlCommand();
                String sumQuery = "SELECT SUM(`prezzo`) FROM `fatturetemp`";
                command.CommandText = sumQuery;
                command.Connection = conn.getConnection();
                command.Parameters.Add("@prezzo", MySqlDbType.Int32).Value = costo;
                conn.openConnection();
                conn.closeConnection();
}

How is the command that give me the result of sumQuery. If i find this command, i can take the result of query and paste in textbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM