Save a table from a bd in a datatable and scroll through your information while taking your data

0

My problem is that I have a table from which I want to take all the fields and convert them into an object. What happens is that I only take the first data of the query I want and I do not know how to go through it. My code is the following

With this I do the query and as I take the whole table

 public static DataTable busqueda()
        {
            DataTable db = new DataTable();
            try
            {

                NpgsqlConnection connection;
                connection = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=root;Database=test;");
                connection.Open();
                string consulta = "SELECT boxnum, partnum, quantity, date, nivel, fila, profundidad FROM market ma INNER JOIN connection cn ON ma.boxnumm = cn.boxnum;";
                NpgsqlCommand com = new NpgsqlCommand(consulta, connection);
                NpgsqlDataAdapter adap = new NpgsqlDataAdapter(com);
                adap.Fill(db);
                connection.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show("Por esto no funciona" + e.Message);
            }
            return db;


        }

then what in a timer I try to start the object, the timer is in case there is any change in the database because it is re starting all the objects but as I have it until now it only takes the first field of my query and then creates infinite objects with the same data, the code is as follows:

private void timer2_Tick(object sender, EventArgs e)
{
    DataTable dt = obtenerTabla.busqueda();
    if (dt.Rows.Count > 0)
    {
        DataRow row = dt.Rows[0]; //guardo datos en variables
        partnum = Convert.ToString(row["partnum"]);
        cantidad = Convert.ToInt32(row["quantity"]);
        profundidad = Convert.ToInt32(row["profundidad"]);
        fila = Convert.ToInt32(row["fila"]);
        boxnum = Convert.ToInt32(row["boxnum"]);
        aux = Convert.ToDateTime(row["date"]);
        cajas.Add(new Caja(partnum,cantidad,profundidad,aux,fila,boxnum));
    }
    else
    {

    }

and then I do not know how to solve it

    
asked by R. Nuñez 13.02.2018 в 20:19
source

1 answer

2

The datatable object must be traversed as if it were an array, you must specify the row number and then the number or column name, you must use a cycle to go through all the values in the table.

for (int i=0; i< dt.Rows.Count; i++)
{
//aca haces las operaciones con cada fila de la tabla ej:
partnum = dt.Rows[i]["partnum"].ToString();
}

On the other hand I do not understand why to refresh the table with a timer unless you are deleting records in your operation

    
answered by 13.02.2018 / 20:32
source