简体   繁体   中英

dataReader reader = cmd.executereader() not working

I am stuck in simple datareader problem .

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;

public void proName(string str)
        {
            SqlDataReader reader;
             using (SqlConnection sqlcon = new SqlConnection(constr))
            {
               string proId = textBox3.Text;

               SqlCommand sqlcmd = new SqlCommand("SELECT proName FROM products where proId = proId;", sqlcon);
               sqlcmd.CommandType = CommandType.TableDirect;
               reader = cmd.executereader();


            }
        }

and it showing error under cmd / command (the name cmd does not exit in current context) .....

I have tried create object before and after connection but not working.

Command type shouldn't be TableDirect .

sqlcmd.CommandType = CommandType.Text; // which is default
reader = sqlcmd.executereader();

The variable name is sqlcmd and you're asking for cmd on the executereader() function.

sqlcmd.CommandType = CommandType.TableDirect;
reader = cmd.executereader();

Should be

sqlcmd.CommandType = CommandType.TableDirect;
reader = sqlcmd.executereader();

Also consider CharithJ's answer, as he stated:

Command type shouldn't be TableDirect.

Below should work..

using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Data.Sql;
        public void proName(string str)
        {
            SqlDataReader reader;
            using (SqlConnection sqlcon = new SqlConnection(constr))
            {
                string proId = textBox3.Text;
                sqlcon.Open();
                SqlCommand sqlcmd = new SqlCommand("SELECT proName FROM products where proId = proId;", sqlcon);
                sqlcmd.CommandType = CommandType.Text;
                reader = sqlcmd.ExecuteReader();
                if (reader.Read())
                {
                    Response.Write(reader[0].ToString());

                }

            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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