2009-08-08 11 views
5

El siguiente es mi procedimiento almacenado.Cómo obtener datatable como resultado del procedimiento almacenado

ALTER PROCEDURE SP_GetModels 
(
    @CategoryID bigint 
) 
AS 
BEGIN 
    Select ModelID,ModelName From Model where [email protected] 
END 

y yo estoy llamando procedimiento almacenado en código detrás como

public SqlConnection conn; 
public SqlDataReader GetModels() 
     { 


     DataTable dt = new DataTable(); 
    public void DbConnection() 
      { 
       conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleCs"].ConnectionString); 
       conn.Open(); 
      } 
       DbConnection(); 
       SqlCommand cmd = new SqlCommand("SP_GetModels", conn); 
       cmd.CommandType = CommandType.StoredProcedure; 
       cmd.Parameters.Add("@CategoryID", SqlDbType.BigInt, 10).Value = CategoryID; 
       // SqlDataAdapter madap = new SqlDataAdapter(cmd, conn); 
       SqlDataReader dreader= cmd.ExecuteReader(); 

       //madap.Fill(dt); 
       return dreader; 
      } 

tengo una lista desplegable a la que tengo que unir objeto DataReader que contienen ModelName. ¿Cómo puedo configurar el origen de datos en DropDownList como datareader

Respuesta

2

Usted debe ser capaz de unirse directamente SqlDataReader a la lista desplegable de esta manera:

MyDropDownList.DataSource = GetModels(); 
MyDropDownList.DataTextField = "ModelName"; 
MyDropDownList.DataValueField = "ModelID"; 

Es necesario especificar también qué miembro (propiedad) va para mostrarse (DataTextField), y cuál se usará como valor cuando se seleccione una entrada en la lista desplegable (DataValueField).

Me recomendamos agarrar los datos de la SqlDataReader en su procedimiento GetModels(), crear instancias de una clase Model el que vayan a ser titulares campos que tiene y necesita, cerca del SqlDataReader, y después lo devuelve como un List<Model> y enlazar esa lista a la lista desplegable. ¡MUCHO mejor que vincular directamente un SqlDataReader!

public class Model 
{ 
    public int ModelID { get; set; } 
    public string ModelName { get; set; } 
} 

Y en sus GetModels():

public List<Model> GetModels() 
{ 
    List<Model> result = new List<Model>(); 

    using(SqlConnection conn = new SqlConnection(ConfigurationManager. 
            ConnectionStrings["SampleCs"].ConnectionString)) 
    { 
    using(SqlCommand cmd = new SqlCommand("SP_GetModels", conn)) 
    { 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.Add("@CategoryID", SqlDbType.BigInt, 10).Value = CategoryID; 

     conn.Open(); 

     using(SqlDataReader dreader = cmd.ExecuteReader()) 
     { 
      while(dreader.Read()) 
      { 
       Model workItem = new Model() 
           { ModelID = dreader.GetInt(0), 
            ModelName = dreader.GetString(1) }; 
       result.Add(workItem); 
      } 
      reader.Close(); 
     } 

     conn.Close(); 
    } 
    } 
    return result; 
} 

Marc

1

En primer lugar, asegúrese de que tiene la datareader se cierran automáticamente al devolverlo:

SqlDataReader dreader= cmd.ExecuteReader(CommandBehavior.CloseConnection); 

une entonces a una lista:

DropDownList1.DataSource = GetModels(); 
DropDownList1.DataValueField = "ModelID"; 
DropDownList1.DataTextField = "ModelName"; 
DropDownList1.DataBind(); 
1

No creo que SqlDataReader herede de IListSource, y si mal no recuerdo, solo puede usar las clases heredadas de IListSource para el enlace de datos. Si desea obtener una DataTable, debe usar un SqlDataAdapter para ejecutar el comando. Ampliando solución de Marc:

public void BindData() 
{ 
    dropDownList1.DataSource = LoadModelData(); 
    dropDownList1.DataValueField = "ModelID"; 
    dropDownList1.DataTextField = "ModelName"; 
    dropDownList1.DataBind(); 
} 
public DataTable LoadModelData() 
{ 
    DataSet dataset = new DataSet(); 
    using (conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleCs"].ConnectionString)) 
    { 
     SqlCommand cmd = new SqlCommand("SP_GetModels", conn); 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.Add("@CategoryID", SqlDbType.BigInt, 10).Value = CategoryID; 
     SqlDataAdapter adapter = new SqlDataAdapter(cmd, conn); 
     adapter.Fill(dataset); 
    } 
    return dataset.Tables[0]; 
} 
0

cómo sobre éste

SqlDataReader dr = cmd.ExecuteReader(); 
      while (dr.Read()) 
      { 
       DropDownList1.Items.Add(new ListItem(dr["ModelName"].ToString(), dr["ModelID"].ToString())); 

      } 
      con.Close(); 
10
private void PopDataBaseName() 
{ 
    try 
    { 
     SqlCommand cmd = new SqlCommand("sp_generate_report", con); 
     cmd.Parameters.Add("@TABLE_NAME", SqlDbType.VarChar,100).Value = TextBox1.Text; 
     cmd.CommandType = CommandType.StoredProcedure; 
     SqlDataAdapter adp = new SqlDataAdapter(cmd); 
     DataSet ds = new DataSet(); 
     adp.Fill(ds); 

    } 
    catch (Exception ex) 
    { 

    } 
} 
+0

¿Qué hay de tener parámetro de salida a partir de t sql lado tabla de datos? cómo obtener el param de salida también? ¿Es posible? ¿Muestra? –

Cuestiones relacionadas