プロジェクトにコードのセクションがあり、使用ブロックを別の使用ブロックの内側にラップしています。これは良い習慣なのか、それともやり過ぎなのか疑問に思います(これは非常に単純なコードのスニペットであることに注意してください。説明のみを目的として使用):
protected void Submit_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
cn.Open();
string cmdStr = "SELECT COUNT(*) FROM REGISTRATION WHERE UserName ='" + this.TextBoxUN.Text + "' ";
using (SqlCommand selectUser = new SqlCommand(cmdStr, cn))
{
int temp = Convert.ToInt32(selectUser.ExecuteScalar().ToString());
if (temp == 0)
{
string insCmd = "Insert INTO REGISTRATION (UserName, Password, EmailAddress, FullName, Country) VALUES (@UserName, @Password, @EmailAddress, @FullName, @Country)";
using (SqlCommand insertUser = new SqlCommand(insCmd, cn))
{
try
{
insertUser.Parameters.AddWithValue("@UserName", this.TextBoxUN.Text);
insertUser.Parameters.AddWithValue("@Password", this.TextBoxPass.Text);
insertUser.Parameters.AddWithValue("@EmailAddress", this.TextBoxEA.Text);
insertUser.Parameters.AddWithValue("@FullName", this.TextBoxFN.Text);
insertUser.Parameters.AddWithValue("@Country", this.DropDownListCountry.SelectedItem.ToString());
insertUser.ExecuteNonQuery();
Response.Redirect("~/Login.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
else
{
Response.Write("User already Exists in Database");
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}