Send information from a Viwer Data grid to sql database

Asked

Viewed 49 times

0

I’m 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 one foreach to scroll through all columns and rows, but how can I assemble this foreach?

  • 1

    put the code you already have ready

3 answers

2


It lacked to give more information and put the code you have tried. Supposing that the bank is the SQlServer, and your grid has 4 columns, would be like this:

I don’t know what kind of data you use, so stick to 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 the ForEachto traverse all lines on the Grid. The dgvProdutos is the Datagridview.

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();
                    }

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

   }

}

Browser other questions tagged

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