how to extract rows from sql table field in String with C #?

0

Good morning, I would like to know how I can extract all the rows of a certain field in variables (String) using C #.

For example:

Campo = Usuario

rows of said field:

Juan   
Ana 
Jose

put them in variables like this:

String nombre1 --> Juan  
String nombre2 --> Ana   
String nombre3 --> Jose

PS: I use sqlserver

PD2: I have the following fields: Id_User , Usuario and Pass

Enclosed current code:

conexion.Open();

        SqlCommand cmd = conexion.CreateCommand();
        SqlDataReader reader = cmd.ExecuteReader();
        reader.Read();
        string nombre = reader.GetString(1);

        int cant = nombre.Count();



conexion.Close();
    
asked by juan quiroz pelaez 02.10.2017 в 07:43
source

1 answer

0

The quick answer is: at compile time you can NOT create variables with that kind of names.

What you can do is create a collection of string s where you can explore the names like this:

nombres[1]

Consider that doing it on a variable of type string[] implies that you know previously (in some way) its final size. If not, consider creating a List<string> to which you can add n number of elements.

DataTable dt;
using (SqlConnection DBCon = new SqlConnection("..."))
{
    using (SqlCommand cmnd = new SqlCommand("SELECT ...", DBCon))
    {
        DBCon.Open();
        using (SqlDataReader reader = cmnd.ExecuteReader())
        {
            dt = new DataTable();
            if (reader.HasRows)
            {
                SqlDataAdapter da = new SqlDataAdapter(cmnd);
                reader.Dispose();
                da.Fill(dt);
            }
        }
    }
}

List<string> nombres = new List<string>();
foreach(DataRow dr in dt.Rows)
{
    nombres.Add(dr["Usuario"].ToString());
}

To go through it, one cycle is enough:

for(int x = 0; x < nombres.Lenght; x++)
{
    Console.WriteLine(nombres[x]);
}
    
answered by 02.10.2017 / 15:35
source