-1

I want to fetch float data (if exist) from database and after addition show the result in text box (TXT_grandtotal)

In my code its shows only numeric value

double price= 0;   
DataTable dt = new DataTable();

cmd.CommandText = "select total from productADD where auto_no='"+txt_autoNo.Text.Trim() + "'";
cmd.Connection = con;

SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    float id = (Convert.ToInt32(row["total"]));
    price = id + price;
    TXT_grandtotal.Text = (Convert.ToString(price));
}
René Vogt
  • 43,056
  • 14
  • 77
  • 99
Travelers
  • 25
  • 4
  • Is total in float type? because this line `float id = (Convert.ToInt32(row["total"]));` is confusing – Saif Aug 29 '19 at 06:30
  • You use `Convert.ToInt32` instead of `Convert.ToSingle()`. And btw: please don't insert user input directly into your query, use **paramterized queries** instead. Your code is open to [SQL injection](https://www.bobby-tables.com) – René Vogt Aug 29 '19 at 06:31
  • I would strongly suggest reading the duplicate link on SQL Injection. Then, read up on Dapper. – mjwills Aug 29 '19 at 06:52
  • What is the **exact** value of `row["total"]`? – mjwills Aug 29 '19 at 06:55
  • lbl_nuToword.Text = NumberToWords(Convert.ToInt32(TXT_grandtotal.Text)); when i want to show the result in word its says the string is not in correct format ? – Travelers Aug 29 '19 at 06:56
  • That is a new question. `NumberToWords` is not in your question. Please write a new question. – mjwills Aug 29 '19 at 06:58

2 Answers2

2

First issue in your code is that you are not using parametrize query, secondly conversion was not correct, please check the following code if it help you

double price= 0;   
DataTable dt = new DataTable();

string sql = "select total from productADD where auto_no = @auto_no";

using (SqlConnection connection = new SqlConnection(/* connection info */))
{
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@auto_no", SqlDbType.Int);
        command.Parameters["@auto_no"].Value = Int32.Parse(txt_autoNo.Text.Trim());
}

SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    float id = (Convert.ToSingle(row["total"]));
    float price = id + price;
    TXT_grandtotal.Text = Convert.ToString(price)
}
Saif
  • 2,611
  • 3
  • 17
  • 37
-2
           cmd.CommandText = "SELECT SUM(CAST(total AS int)) AS total from productADD where auto_no='"+txt_autoNo.Text.Trim() + "'";

            cmd.Connection = con;

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(dt);

            TXT_grandtotal.Text=Convert.ToString(dt.Rows[0]["total"]);

Note:-- You can Follow this method...here i'm Calculating the total Value...instead of using for Loop...

This will improve your performance..

you can use cast if your table data type as varchar

THE LIFE-TIME LEARNER
  • 1,476
  • 1
  • 8
  • 18