[英]Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource
i have a function that get a DropDownList , should run a store procedure and get back a Supplires names taht should be displayes at the dropdownlsit . 我有一个获取DropDownList的函数,应该运行一个存储过程,并获取一个应该在dropdownlsit上显示的供应商名称taht。
This is the function : 这是功能:
public void LoadSuppliers(DropDownList ddl , int num)
{
con = connect("igroup9_test1ConnectionString");
using (SqlCommand sqlComm = new SqlCommand("[spGetSuppliers]", con))
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.Parameters.AddWithValue("@RowMeterialID ", num);
sqlComm.CommandTimeout = 600;
ddl.DataSource = sqlComm;
sqlComm.ExecuteNonQuery();
ddl.DataBind();
ddl.DataTextField = "sName";
ddl.DataValueField = "sName";
}
catch (Exception ex)
{
throw (ex);
}
}
}
And this is the procedure: 这是过程:
USE [igroup9_test1]
GO
/****** Object: StoredProcedure [dbo].[spGetSuppliers] Script Date: 03/24/2014 18:13:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[spGetSuppliers]
(
@RowMeterialID int
)
as
begin
select distinct sName
from Supplier, RawMaterials, SupplierRawMaterials
where RawMaterials.rmID=@RowMeterialID and RawMaterials.rmID=SupplierRawMaterials.rmID and SupplierRawMaterials.SupplierID=Supplier.SupplierID
end
When i'm running the program it throw an error: 当我运行程序时,会引发错误:
System.InvalidOperationException: Data source is an invalid type.
System.InvalidOperationException:数据源是无效的类型。 It must be either an IListSource, IEnumerable, or IDataSource.
它必须是IListSource,IEnumerable或IDataSource。
You cannot assign ddl.DataSource = sqlComm
since it is a SqlCommand. 您不能分配
ddl.DataSource = sqlComm
因为它是SqlCommand。
Fill a DataSet
and assign 填充
DataSet
,并分配
ddl.DataSource = dsMyResult;
You're trying to assign the instance of SqlCommand
directly to your DataSource
: 您试图将
SqlCommand
实例直接分配给您的DataSource
:
ddl.DataSource = sqlComm;
I'm not sure if that's a typo or you thought it would automatically run the stored procedure and assign the results to the control, but it won't work. 我不确定这是否是错字,或者您认为它会自动运行存储过程并将结果分配给控件,但是它不起作用。
Also, ExecuteNonQuery()
isn't the correct method to call, if your looking to get records back. 另外,如果您希望取回记录,则
ExecuteNonQuery()
也不是正确的调用方法。 Try ExecuteReader()
instead: 尝试使用
ExecuteReader()
:
var reader = sqlComm.ExecuteReader();
while (reader.Read())
{
// Do something with the data
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.