Obed Silva
Obed Silva

Reputation: 19

Query data from table using reader

Currently I try retrieve data of a register of a table but it doesn't retrieve anything, Any idea?. I don't know if my script is wrong or i'm missing something. don't Capture nothing. Also i try with this query but i don't know if the Where is the correct form? SqlCommand comm = new SqlCommand("select clase, operacion from Clase_Documento where codigoafip = '"+ codafip +"' ", conn);

Field codafip = (Field)doc.Fields["ZIMCodigoAFIP"];
Field clasedoc = (Field)doc.Fields["ZIMBlart"];
Field operacion = (Field)doc.Fields["ZIMOperacion"];

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=localhost\\DOKUSTAR;Database=RdaDB10;User ID=bcc;Password=******;Trusted_Connection=Yes";
conn.Open();

SqlDataReader dr;
SqlCommand comm = new SqlCommand("select * from Clase_Documento", conn);
dr = comm.ExecuteReader();
while(dr.Read())
{
    if (codafip.Value == dr.GetString(4))
    {   
        string clasedoc2 = dr.GetString(1);
        string operacion2 = dr.GetString(5);
        clasedoc.Value = clasedoc2; //here put the data of the table in its respective field
        operacion.Value = operacion2; //here put the data of the table in its respective field
    }
}

Only to clarify, mi table is this, and the field that I want retrieve is "clase" and "operacion" depending of parameter codigoafip enter image description here

Upvotes: 0

Views: 119

Answers (1)

Cetin Basoz
Cetin Basoz

Reputation: 23797

Assuming your field names were claseDocField, operacionField and codafipField (and all string):

using (SqlConnection conn = new SqlConnection(@"server=.\DOKUSTAR;Database=RdaDB10;Trusted_Connection=Yes"))
using (SqlCommand comm = new SqlCommand(@"select top(1) clasedocField, operacionField
from Clase_Documento
where codafipField = @codafip", conn))
{
 comm.Parameters.Add("@codafip", SqlDbType.VarChar).Value = codafip.Value;
 conn.Open();

  SqlDataReader dr = comm.ExecuteReader();
  if(dr.Read())
  {
        clasedoc.Value = (string)dr["claseDocField"];
        operacion.Value = (string)dr["operacionField"];
  }
}

EDIT:

    using (SqlConnection conn = new SqlConnection(@"server=.\DOKUSTAR;Database=RdaDB10;Trusted_Connection=Yes"))
    using (SqlCommand comm = new SqlCommand(@"select top(1) clase, operacion
    from Clase_Documento
    where codigoafip = @codafip", conn))
    {
     comm.Parameters.Add("@codafip", SqlDbType.VarChar).Value = codafip
;
     conn.Open();

      SqlDataReader dr = comm.ExecuteReader();
      if(dr.Read())
      {
            clasedoc.Value = (string)dr["clase"];
            operacion.Value = (string)dr["operacion"];
      }
      else 
      {
           clasedoc.Value = "Not found";
      }
    }

Upvotes: 2

Related Questions