How to fill array from a datatable

0

I'm doing an insertion of data from a sql database to a datatable to then dump that data into an arraylist that will contain and remove the rows, when executing the visual it collects the columns and goes into interruption and I can not find out why

string query = "select idpedido,provincia,cliente,datediff(fecha_penalizacion,sysdate()) as 'dias restantes',fecha_inicio,fecha_penalizacion from pedido";




            MySqlDataAdapter dataAdapter = new MySqlDataAdapter(query, connection);
            MySqlDataAdapter dataAdapter2 = new MySqlDataAdapter(query2, connection);

            button1.Enabled = true;

            connection.Open();

            dataAdapter.Fill(TablaPedidos);
            //Crear objetos "Ordenes"
            foreach (DataRow row in TablaPedidos.Rows)
            {

                MyArray.Add(new Ordenes(row["idpedido"].ToString(), row["cliente"].ToString(), row["provincia"].ToString(), row["dias restantes"].ToString()

                , row["fecha_inicio"].ToString(), row["fecha_penalizacion"].ToString()));

            }

            connection.Close();
        }
        catch (SystemException) { MessageBox.Show("i got deaded bro"); };

            MessageBox.Show("Se han recogido " + MyArray.Count() + " columnas");





for(int i = 0;i < MyArray.Count();i++) {
                string mensajeContenidoSimple="<tr bgcolor=" + colorJard + "><td>" + MyArray[i].provincia + "</td><td>" + MyArray[i].Numorden + "</td><td>" + MyArray[i].Nomcliente.ToString().Substring(0, 10) + "..." + "</td><td>" + MyArray[i].Restan + "</td><td>" + "</td></tr>";
                mensajeContenidoSimple += mensajefull;
            }
    
asked by luiso 25.05.2018 в 06:44
source

1 answer

2

The exception as indicated in the comments is the following:

  

The index and length must refer to a location in the chain.   Parameter name: length

This error is very clear. You are trying to get a substring indicating a larger size of the available one.

In your case, this is the problematic sentence:

MyArray[i].Nomcliente.ToString().Substring(0, 10)

If Nomcliente is smaller than 10 characters, it will throw that exception to you.

What you can do is use the ternary operator ?: to check the size before doing the SubString :

MyArray[i].Nomcliente.ToString() < 10 ? 
              MyArray[i].Nomcliente.ToString() 
             :MyArray[i].Nomcliente.ToString().Substring(0, 10);
    
answered by 25.05.2018 в 10:58