各位前輩好,小弟是ASP.NET C# 新手最近寫了幾個程式雖然功能都正常,但是對於程式簡化這部分就不是很懂,例如在Button Click Event內有許多判斷,不知道怎麼簡化程式,還請各位前輩先進指教
protected void ImageButton2_Click(object sender, EventArgs e)
{
this.InnerBindGrid();
foreach (GridViewRow row in GridView3.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
SqlDataReader reader = null;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("select * from [B] where ([A] = 'ABC' OR [B] = 'CDE') AND User_Name=@User_Name", con);
TextBox A_name = (TextBox)row.FindControl("A_name");
cmd.Parameters.AddWithValue("@User_Name", A_name.Text);
reader = cmd.ExecuteReader();
if (reader != null && reader.HasRows && TextBox28.Text == string.Empty)
{
Response.Write("<Script language='JavaScript'>alert('請確認!');</Script>");
Q13CheckBox.BorderColor = System.Drawing.Color.Red;
Q13CheckBox.BorderWidth = 2;
TextBox21.BorderColor = System.Drawing.Color.Red;
TextBox21.BorderWidth = 2;
TextBox28.BorderColor = System.Drawing.Color.Red;
TextBox28.BorderWidth = 2;
Consultation_Label.BorderColor = System.Drawing.Color.Red;
Consultation_Label.BorderWidth = 2;
btnShowPopup.Visible = true;
ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup();", true);
return;
}
con.Close();
}
}
int rowCount = InnerGridView.Rows.Count;
if (rowCount == 0)
{
btnShowPopup.Visible = true;
ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup();", true);
return;
}
if(this.TextBox28.Text != string.Empty && rowCount != 0)
{
SqlDataReader reader = null;
SqlConnection con = new SqlConnection(Consultation_constr);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM B WHERE [A]=@A AND [B]=@B AND [C]='7304' AND [D]=@D;", con);
cmd.Parameters.AddWithValue("@A", this.TextBox1.Text);
cmd.Parameters.AddWithValue("@B", this.Dr_Code.Text);
cmd.Parameters.AddWithValue("@D", this.TextBox28.Text);
reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Response.Write("<Script language='JavaScript'>alert('請確認日期!');</Script>");
btnShowPopup.Visible = true;
ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup();", true);
return;
}
con.Close();
}
if (TextBox1.Text == string.Empty || TextBox5.Text == string.Empty)
{
string script = "alert('請輸入申請人資料!!');";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true);
}
else
{
User_infor();
Client_info();
Submit();
}
}
與其說是簡化,倒不如多找幾個方法將你想呈現的東西,用不同的方法來敘述,不僅可以增加自己的經驗,也可以比對看看,哪個工具比較方便,既然都有初始版本了,就做個第二版、第三版出來吧,多做幾次自然,做熟一點,大概就知道哪些地方可以簡化了