Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# dataGridView CommandText属性尚未在c中初始化#_C#_C# 4.0 - Fatal编程技术网

C# dataGridView CommandText属性尚未在c中初始化#

C# dataGridView CommandText属性尚未在c中初始化#,c#,c#-4.0,C#,C# 4.0,您好,我已经在dataGridView中为windowsform编写了一段代码 如下 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString); SqlCommand sqlCmd = new SqlCommand(); sqlCmd.Connection = con; con.Open(); sqlCmd.Comma

您好,我已经在dataGridView中为windowsform编写了一段代码 如下

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
con.Open();
sqlCmd.CommandType = CommandType.Text;
SqlCommand CommandText = new SqlCommand("SELECT * FROM report", con);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);//its pointing to this line and says ExecuteReader: CommandText property has not been initialized.
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = dtRecord;   

请告诉我代码中的问题是什么?

将CommandText分配给已定义的命令,而不是用于创建新的
SqlCommand

sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "SELECT * FROM report";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
使用适配器填充数据表不需要定义命令;您可以使用以下代码简单地执行相同的操作:

  SqlDataAdapter sqlDataAdap = new SqlDataAdapter("SELECT * FROM report", con);
  DataTable dtRecord = new DataTable();
  sqlDataAdap.Fill(dtRecord);

请阅读有关的详细信息,因为您从未在
sqlCmd
上设置
CommandText
属性。相反,您创建了第二个
SqlCommand
对象:

SqlCommand CommandText = new SqlCommand("SELECT * FROM report", con);
你从来没用过

听起来好像您想在已有的对象上设置
CommandText
属性:

sqlCmd.CommandText = "SELECT * FROM report";