How to pass data from select to an array

Asked

Viewed 87 times

1

How to save the select data down to an array

 SqlConnection conConexao1 = clsdb.AbreBanco();
 SqlCommand cmd1 = new SqlCommand("select id, tamplete1, tamplete2 from usuarios ", conConexao1);
 SqlDataReader dr1 = cmd1.ExecuteReader();
 if (dr1.HasRows == true)
 {
    if (dr1.Read())
    {
        id = int.Parse(dr1[0].ToString());
        templete1  = (dr1[1].ToString());
        templete2 = (dr1[2].ToString());
    }
 }

2 answers

2

Function can be changed if, for while, where you will go through the.

while (dr1.Read())
{
    id = int.Parse(reader.GetOrdinal("id"));
    templete1  = (reader.GetOrdinal("tamplete1"));
    templete2 = (reader.GetOrdinal("tamplete2"));
}

Explaining to you why: As says the Documentation:

The method SqlDataReader.Read() advances the SqlDataReader to the next record and returns true if there are more lines, otherwise return false.

1


To save data from a row of an Sqldatareader in an array use the method SqlDataReader.GetValues to populate the object array with the values of the current line.

 SqlConnection conConexao1 = clsdb.AbreBanco();
 SqlCommand cmd1 = new SqlCommand("select id, tamplete1, tamplete2 from usuarios ", conConexao1);
 SqlDataReader dr1 = cmd1.ExecuteReader();

 while (dr1.Read())
 {
     //Array para receber os dados
     Object[] array_dr1 = new Object[dr1.FieldCount];      

     //Preenche a array com os dados  
     dr1.GetValues(array_dr1);
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.