简体   繁体   中英

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 .

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. It must be either an IListSource, IEnumerable, or IDataSource.

You cannot assign ddl.DataSource = sqlComm since it is a SqlCommand.

Fill a DataSet and assign

ddl.DataSource = dsMyResult;

You're trying to assign the instance of SqlCommand directly to your 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. Try ExecuteReader() instead:

var reader = sqlComm.ExecuteReader();

while (reader.Read())
{
    // Do something with the data
}

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