简体   繁体   English

C#ExecuteReader不返回ASP.Net中的SQL查询数据

[英]C# ExecuteReader not returning SQL query data in ASP.Net

I'm having trouble extracting the SQL data I need from the below query. 我无法从以下查询中提取所需的SQL数据。 I've looked on MSDN and followed their examples, but for some reason the executereader is not reading the data and returning it to the textbox, after clicking the button. 我查看了MSDN并遵循了它们的示例,但是由于某些原因,executereader并未在单击按钮后读取数据并将其返回到文本框。 I have added a response to ensure the connection is open, and it is each time pressed. 我添加了一个响应以确保连接是打开的,并且每次都按下它。 This is an extract of the code, the only thing I have omitted from here is the sqlconnection detail: 这是代码的一部分,我在这里省略的唯一是sqlconnection详细信息:

protected void Button1_Click(object sender, EventArgs e)
{
        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {

            //set up the SQL command       
            SqlCommand command = new SqlCommand("Use Waste_Test; select * from Bidston_HWRC where MCN_No = @MCN", conn);

            //open the server connection
            conn.Open();

            //define parameter for SQL query
            command.Parameters.Add("@MCN", SqlDbType.Int);
            command.Parameters["@MCN"].Value = TextBox17.Text;

            Response.Write("<script>alert('You are connected')</script>");


            //Execute the query on the server
            SqlDataReader rdr = command.ExecuteReader();

            Response.Write("<script>alert('It's worked')</script>");

            while (rdr.Read())
            {
                TextBox6.Text = rdr["Waste_Description"].ToString();
            }
        }
    }

first of all, you need to use HasRows in order to ensure that query return some result, if no record return then you can show a message in label. 首先,您需要使用HasRows以确保查询返回某些结果,如果没有记录返回,则可以在标签中显示一条消息。 Since you are getting the MCN value from textbox, then you need to parse it into int. 由于您是从文本框中获取MCN值的,因此您需要将其解析为int。 Try the following code. 请尝试以下代码。

protected void Button1_Click(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {     
            SqlCommand command = new SqlCommand("select * from Bidston_HWRC where MCN_No = @MCN", conn);
            conn.Open();
            Command.Parameters.AddWithValue("@MCN", Int32.Parse(TextBox17.Text));
            //Execute the query on the server
            SqlDataReader rdr = command.ExecuteReader();



        if(rdr.HasRows)
        {
            while (rdr.Read())
            {
              TextBox6.Text = rdr["Waste_Description"].ToString();
            }

        }
        else
        {
          // show 'no records found'
        }
       rdr.Close();
       conn.Close();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM