位置0没有排......我该怎么做..?

时间:2013-09-22 07:19:09

标签: c# asp.net

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

            }

1 个答案:

答案 0 :(得分: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);
     }
 }