Send information from a Data grid Viwer to sql database [closed]

0

I am putting together an order form using C # .

The problem is that when I try to send the products that are listed in the Data Grid Viewer to the database, the program reads only the line where the cursor is.

I know I need a foreach to go through all the columns and rows, but how can I mount this structure to foreach ?

    
asked by anonymous 24.04.2018 / 03:04

3 answers

2

You have to give more information and put the code that you have tried. Assuming the bank is SQlServer , and your grid has 4 columns, it would look like this:

I do not know what kind of data you're using, so watch out for the fields. The contents of the cells will have the return type object .

void AddPedidos()
{
   string sqlQuery;
   string strConexao = "Seu caminho para o banco";

   try
   {
      SqlConnection Conexao = new SqlConnection(strConexao);
      Conexao.Open();

      foreach (DataGridViewRow linha in dgvProdutos.Rows)
      {
         qlQuery = $"INSERT INTO Pedidos(ID, Emissao, ProdutoID, Quantidade) VALUES({linha.Cells[0].Value}, {linha.Cells[2].Value}, {linha.Cells[3].Value}, {linha.Cells[4].Value})";

         SqlCommand Comando = new SqlCommand(sqlQuery, Conexao);
         Comando.ExecuteNonQuery();
       }
       Conexao.Close();
   }
   catch (SqlException erro)
   {
      MessageBox.Show($"Ocorreu um erro: {erro.Message}");
   }        
}

You can use ForEach to traverse all rows in the grid. The dgvProdutos is the DataGridView.

    
24.04.2018 / 04:35
0
  void AddPedidos(DataGridView dgvPedido)
  {

   for(int i=0;i<dgvPedido.rowcount;i++){

    string pos0=dgvPedido[0,i].value.ToString();
    string pos1=dgvPedido[1,i].value.ToString();

    //insira o código para invaiar os dados na base de dados

   }

}
    
24.04.2018 / 12:13
0
         //Segue um exemplo usando o entityframework: 
                    ExtratoCentroCusto centroCusto = new ExtratoCentroCusto();
                    foreach (DataGridViewRow dr in GridRateio.Rows)
                    {
                        centroCusto.Valor = Convert.ToDecimal(dr.Cells[0].Value.ToString());
                        centroCusto.IdPlanoConta = int.Parse(dr.Cells[1].Value.ToString());
                        centroCusto.PlanoConta = dr.Cells[1].FormattedValue.ToString(); //pegando o valor da celula
                        db.ExtratoCentroCusto.Add(centroCusto);
                        db.SaveChanges();
                    }
    
24.04.2018 / 14:59