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

C# C ExecuteReader在ASP.Net中不返回SQL查询数据,c#,sql,asp.net,C#,Sql,Asp.net,从下面的查询中提取所需的SQL数据时遇到问题。我查看了MSDN并遵循了它们的示例,但由于某种原因,executereader在单击按钮后没有读取数据并将其返回到文本框。我添加了一个响应,以确保连接是打开的,并且每次按下时都是打开的。这是代码的摘录,我在这里唯一省略的是sqlconnection细节: protected void Button1_Click(object sender, EventArgs e) { using (SqlConnection conn = new

从下面的查询中提取所需的SQL数据时遇到问题。我查看了MSDN并遵循了它们的示例,但由于某种原因,executereader在单击按钮后没有读取数据并将其返回到文本框。我添加了一个响应,以确保连接是打开的,并且每次按下时都是打开的。这是代码的摘录,我在这里唯一省略的是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();
            }
        }
    }

首先,您需要使用HasRowsin来确保查询返回一些结果,若并没有记录返回,那个么您可以在标签中显示一条消息。由于您是从textbox获取MCN值,因此需要将其解析为int

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

你说参数是int类型,然后给它一个字符串,也许这与此有关?尝试使用command.Parameters.AddWithValueMCN,TextBox17.Text;考虑Lasse V.Karlsen提到的铸件类型为int。若参数的必需类型为整数,为什么在rdr.Read仅为一个值时循环?如果rdr.Read TextBox6.Text=rdr[Waste\u Description].ToString;command.Parameters[@MCN].Value=int.ParseTextBox17.Text;您是否在SQL server中测试了查询?你有什么结果吗?你确定这个代码有效吗?我猜它会在这一行->command.Parameters[@MCN].Value=Int32.ParseTextBox17.Text中抛出一个IndexOutOfRangeException;刚刚更改为Command.Parameters。AddWithValue@MCN,Int32.ParseTextBox17.Text;我试着将文本解析成int,因为值必须是int…您好@Pikoh,您是对的,它确实抛出了那个错误。你将如何纠正这一点?Thanks@kehoewex86使用AddWithValue或使用add和then.Value=int.ParseTextBox17.Text使用saif更新的答案@很高兴听到这个消息