1
votes

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0165: Use of unassigned local variable 'Username'

The c# code:

SqlCommand NewUser = new SqlCommand("INSERT INTO [DeleteUser] Values (@username,@password,@name,@lastname,@location,@profesion,@email,@gender,@money,@pro,@xp,@lv,@m1,@m2,@m3,@m4,@m5,@d1,@d2,@d3,@d4,@d5);", c);
NewUser.Connection = c;

NewUser.Parameters.AddWithValue("@username", Username);
NewUser.Parameters.AddWithValue("@password", Pasword);
NewUser.Parameters.AddWithValue("@name", FName);
NewUser.Parameters.AddWithValue("@lastname", LName);
NewUser.Parameters.AddWithValue("@location", Location);
NewUser.Parameters.AddWithValue("@profesion", Profesion);
NewUser.Parameters.AddWithValue("@email", email);
NewUser.Parameters.AddWithValue("@gender", gender);
NewUser.Parameters.AddWithValue("@money", money);
NewUser.Parameters.AddWithValue("@pro", property);
NewUser.Parameters.AddWithValue("@xp", xp);
NewUser.Parameters.AddWithValue("@lv", level);
NewUser.Parameters.AddWithValue("@m1", mission1);
NewUser.Parameters.AddWithValue("@m2", mission2);
NewUser.Parameters.AddWithValue("@m3", mission3);
NewUser.Parameters.AddWithValue("@m4", mission4);
NewUser.Parameters.AddWithValue("@m5", mission5);
NewUser.Parameters.AddWithValue("@d1", did1);
NewUser.Parameters.AddWithValue("@d2", did2);
NewUser.Parameters.AddWithValue("@d3", did3);
NewUser.Parameters.AddWithValue("@d4", did4);
NewUser.Parameters.AddWithValue("@d5", did5);

c.Open();
NewUser.ExecuteNonQuery();
c.Close();
2
Where is the definition of Username? - Yacoub Massad
You should check out Can we stop using AddWithValue() already? and stop using .AddWithValue() - it can lead to unexpected and surprising results... - marc_s

2 Answers

0
votes

Compiler Error Message: CS0165: Use of unassigned local variable 'Username'

This error gives you when you declare the Username inside the method. You need to assign first a default value to it before, assigning the actual value you want

Demo:

public void InsertMethod()
{
   string Username;
   //string Username="";      it should be like this

   MessageBox.Show(Username);// this will give you error of "unassigned local variable"
}

P.S. Better to use

NewUser.Parameters.Add("@parameterName",SqlDbType.VarChar).Value = "somevalue"

Than using this:

NewUser.Parameters.AddWithValue("@username", Username);

This one will give you error especially when it comes to date, time and bulk insert/update.

0
votes

Username might be null

if (Username  == null)
{
    NewUser.Parameters.AddWithValue("@username", DBNull.Value);
}
else
{
    NewUser.Parameters.AddWithValue("@username", Username);
}