I have this code snippet:
The variable m is a string set as the Name returned by the first sql command, that is closed and then the second is used to return other details. At this point m is used to populate the view, but visual studio says it is an unassigned variable. How do I fix this?
SqlCommand mcom = new SqlCommand("SELECT * FROM [Rica].[dbo].[MaritialStatus] WHERE ID=" + myReader["MaritalStatusID"], mnner);
SqlDataReader mread = null;
mread = mcom.ExecuteReader();
while (mread.Read())
{
m = mread["Name"].ToString();
}
mnner.Close();
user_table.Text = user_table.Text + "<tr><td>"+ myReader["PostCode"] +"</td>";
//user details
SqlConnection inner = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RicaConnectionString"].ConnectionString);
inner.Open();
SqlCommand icom = new SqlCommand("SELECT * FROM [Rica].[dbo].[User] WHERE ID=" + myReader["ID"], inner);
SqlDataReader iread = null;
iread = icom.ExecuteReader();
while (iread.Read())
{
user_table.Text = user_table.Text + "<td>" + iread["NamePrefix"] + " " + iread["FirstName"] + " " + iread["LastName"] + "</td><td>" + iread["Username"] + "</td><td>" + g + "</td><td>" + m + "</td></tr>";
}
iread.Close();
The compiler is entirely correct that
mis unassigned. For example, there could be no rows returned. Just set an initial value that you want to use for the no-rows case, for example:More specifically, for an assignment in a
while/foreachetc, the “definite assignment” after thewhile/foreachis the same as the “definite assignment” before, because it is possible that no iterations were performed (i.e. aforeachover an empty set, orwhilewhere the test returnsfalseimmediately).I must also observe that there are lots of problems in your current code; lots of missing
using, SQL injection vulnerabilities (these are potentially big problems), etc, xss vulnerabilities (this is also a huge problem).Using a tool like dapper-dot-net would fix the SQL injection, allowing really easy parameterization and reading, with it handling correct disposal of the command / reader. The xss issue should be addressed by html-encoding correctly. Although in truth, it is rare to have SQL code and HTML code right next to each-other like this.