2013-09-22 62 views
0
protected void Button3_Click(object sender, EventArgs e) 
    { 
     { 
      if (TexBo_num.Text == "" && TexBo_num.Text != "contact_no") 
      { 
       ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Either contact_number is empty or Wrong');", true); 
      }else 

      { 
      SqlConnection con = new SqlConnection(@"Data Source=SYSTEM2\SQLEXPRESS;Initial Catalog=amresh;Integrated Security=True"); 
      con.Open(); 
      SqlDataAdapter value = new SqlDataAdapter("Select * FROM detail WHERE contact_no ="+TexBo_num.Text, con); 
      DataSet val = new DataSet(); 
      value.Fill(val); 

      if ((val.Tables[0].Rows[0]["contact_no"]).ToString() == TexBo_num.Text) 
      { 

       SqlDataAdapter da = new SqlDataAdapter("select name,address from detail where contact_no =" + TexBo_num.Text, con); 
       DataSet ds = new DataSet(); 
       da.Fill(ds); 
       string nam = ds.Tables[0].Rows[0]["name"].ToString(); 
       string add = ds.Tables[0].Rows[0]["address"].ToString(); 
       TxtBox_name.Text = nam; 
       TexBo_add.Text = add; 
      }else 

      { 
       ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('value not found');", true); 
      } 


       con.Close(); 
      } 

      } 
+0

必須調試:) –

回答

0

如果帶有contact_no的文本框包含的值不存在於detail表中,那麼您沒有任何由SqlDataAdapter填充方法返回的行。但你可以用這個檢查

if (val.Tables[0].Rows.Count > 0) 
{ 
    TxtBox_name.Text = val.Tables[0].Rows[0]["name"].ToString(); 
    TexBo_add.Text = val.Tables[0].Rows[0]["address"].ToString(); 
} 

請注意,不需要再次查詢數據庫以從表格細節中檢索名稱和地址。您在val數據集中已有該信息。

說的是,記得總是避免字符串連接來組成一個sql命令文本,但總是使用一個參數化查詢。這將消除Sql Injection安全問題的任何可能性。

概括你的代碼可以改寫爲

// Ask to return just the data you need, not the whole rows 
string commandText = "select name,address from detail where contact_no = @num"); 
using(SqlConnection con = new SqlConnection(....)) 
using(SqlCommand cmd = new SqlCommand(commandText, con)) 
{ 
    con.Open(); 
    cmd.Parameters.AddWithValue("@num", Convert.ToInt32(TexBo_num.Text)); 
    using(SqlDataAdapter value = new SqlDataAdapter(cmd)) 
    { 
     DataSet val = new DataSet(); 
     value.Fill(val); 
     if (val.Tables[0].Rows.Count > 0) 
     { 
      TxtBox_name.Text = val.Tables[0].Rows[0]["name"].ToString(); 
      TexBo_add.Text = val.Tables[0].Rows[0]["address"].ToString(); 
     } 
     else 
      ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('value not found');", true); 
    } 
}