1
 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();
            }

            }
4

1 回答 1

1

如果带有 的文本框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 注入安全问题的任何可能性。

总结您的代码可以重写为

// 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);
     }
 }
于 2013-09-22T07:31:24.380 回答