试图填充数据表时出错

本文关键字:出错 数据表 填充 | 更新日期: 2023-09-27 18:17:37

这是我的语法,但我得到一个错误

在调用'Fill'之前没有初始化SelectCommand属性。

为了能够填充数据表,我需要做什么?

using (SqlConnection conn = new SqlConnection("Server=Test;Database=Test;Integrated Security=SSPI;"))
{
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM [dbo].[selfservice] WHERE saleID = @userid;";
command.Parameters.Add("@userid", SqlDbType.VarChar);
command.Parameters["@userid"].Value = row.Field<string>("saleID");
command.Connection = conn;                    
using (SqlDataAdapter dataadapter1 = new SqlDataAdapter()
{
    dataadapter1.Fill(dtData);
}
}

试图填充数据表时出错

注意,您没有使用command对象。您需要向适配器添加select命令:

using (SqlDataAdapter dataadapter1 = new SqlDataAdapter()
{
    dataadapter1.SelectCommand = command
    dataadapter1.Fill(dtData);
}

您必须在Fill之前指定SqlDataAdapter的select command,并且您在末尾缺少一个右括号

using (SqlDataAdapter dataadapter1 = new SqlDataAdapter())
{
    dataadapter1.SelectCommand=command; 
    dataadapter1.Fill(dtData);
}