0

I want to create code where if for example the dropdown list is = to linemen then his monthly salary is = 6000 and I want this to be put into monthly salary column in my database.

Here is the code - with this code I get error in monthlysalary parameters saying

use of unassigned local variable total

Code:

float total;

if (Designation.SelectedValue == "Linemen")
{
    total = 4000;
}

if (Designation.SelectedValue == "Manager")
{
    total = 6000;
}

if (Designation.SelectedValue == "Boss")
{
    total = 8000;
}

string emp = datapayemp.SelectedRow.Cells[1].Text;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
string command = "INSERT INTO PAYROLL(RegEmpID, MonthlySalary) VALUES (@RegEmpID, @MonthlySalary)";

SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("@RegEmpID", emp);
cmd.Parameters.AddWithValue("@MonthlySalary",total);

try
{
    con.Open();
    cmd.ExecuteNonQuery();                
}
finally
{
    con.Close();
}
1
  • i put 'float total' above the if else Commented Apr 29, 2018 at 6:45

1 Answer 1

1

Well, the problem is: you're not initializing total to any value - and if the Designation.SelectedValue is neither Linemen, Manager nor Boss, then there's never any value assigned to total.

You need to give that total an initial value, just in case none of the if clauses match:

float total = 0.0;

Also: float is notorious for rounding errors etc. - so if you're dealing with money values, I would strongly recommend to use the decimal datatype instead. Same goes for the SQL Server database table: don't use FLOAT or REAL - use DECIMAL(p,s) instead

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.