Write data from a Datagridview

Asked

Viewed 433 times

1

Hello

I have this Datagridview below:

DataGridView produtos

I need to go through Datagrid, check which checkbox is marked and save the data (Quantity: Qty and Product Code: cod_product). I managed with Stack’s help to make this code below:

private void btnIncluir_Click(object sender, EventArgs e )
 {
     try{

            int cod;
            int qntd;
            foreach (DataGridViewRow linha in dgvSolicitacaoCliente.Rows)
            {
             var cell = linha.Cells[0] as DataGridViewCheckBoxCell;
              if ((bool)cell.Value)
              {
                  cod = Convert.ToInt32(linha.Cells[4].Value.ToString());
                  qntd = Convert.ToInt32(linha.Cells[1].Value.ToString());

                  cmd.CommandText = "insert into solicitacao_item (cod_solicitacao_cliente, cod_produto, qtd) VALUES (@cod_solicitacao_cliente, @cod_produto, @qtd)";
                  cmd.Parameters.Add(new NpgsqlParameter("@cod_solicitacao_cliente", cmd.CommandText = "select MAX(cod_solicliente) from solicitacao_cliente")); 
                  cmd.Parameters.Add(new NpgsqlParameter("@cod_produto", cod));
                  cmd.Parameters.Add(new NpgsqlParameter("@qtd", qntd));

                  cmd.ExecuteNonQuery();
                  conexao.desconecta(cmd.Connection);

               }
            }
            MessageBox.Show("Incluso com sucesso!");
        }
        catch (Exception ex) // Caso de erro, irá mostrar a mensagem de erro!
       {
           MessageBox.Show(ex.ToString()); // mensagem de erro
       }
 }

But give this error right in this part of the code: if ((bool)cell.Value):

System.NullReferenceException was unhandled
HResult=-2147467261
Message=Referência de objeto não definida para uma instância de um objeto.
Source=Vendas Diretas Versao Atualizada
StackTrace:
   em Vendas_Diretas_Versao_Atualizada.frmSolicitacaoCliente.btnIncluir_Click(Object sender, EventArgs e) na c:\Users\WILL\Documents\Visual Studio 2013\Projects\Vendas Diretas Versao Atualizada\Vendas Diretas Versao Atualizada\Solicitacao Cliente.cs:linha 87
   em System.Windows.Forms.Control.OnClick(EventArgs e)
   em System.Windows.Forms.Button.OnClick(EventArgs e)
   em System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   em System.Windows.Forms.Control.WndProc(Message& m)
   em System.Windows.Forms.ButtonBase.WndProc(Message& m)
   em System.Windows.Forms.Button.WndProc(Message& m)
   em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   em System.Windows.Forms.Application.RunDialog(Form form)
   em System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
   em System.Windows.Forms.Form.ShowDialog()
   em Vendas_Diretas_Versao_Atualizada.frmPrincipal.clientesToolStripMenuItem1_Click(Object sender, EventArgs e) na c:\Users\WILL\Documents\Visual Studio 2013\Projects\Vendas Diretas Versao Atualizada\Vendas Diretas Versao Atualizada\Principal.cs:linha 83
   em System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
   em System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
   em System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
   em System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
   em System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
   em System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
   em System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
   em System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
   em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   em System.Windows.Forms.Control.WndProc(Message& m)
   em System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   em System.Windows.Forms.ToolStrip.WndProc(Message& m)
   em System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
   em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   em System.Windows.Forms.Application.Run(Form mainForm)
   em Vendas_Diretas_Versao_Atualizada.Program.Main() na c:\Users\WILL\Documents\Visual Studio 2013\Projects\Vendas Diretas Versao Atualizada\Vendas Diretas Versao Atualizada\Program.cs:linha 19
   em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   em System.Threading.ThreadHelper.ThreadStart()
InnerException: 
  • you are trying to access a value of a field that is null... right in your if ..try like this if ((cell.HasValue && (bool)cell.Value)

  • 2

    Come on, maybe the Cells[0] is not the column with the CheckBox. When you do linha.Cells[0] as DataGridViewCheckBoxCell; a conversion attempt is made and if this conversion fails, it will be returned null. You already know what’s going wrong, now switch Cells[0] for Cells["nomeDaColuna"] and testing.

  • @Williansantos you can do as follows .. foreach (GridViewRow row in dgvSolicitacaoCliente.Rows)
 {
 CheckBox Cbx = (CheckBox)row.FindControl("cbxselecione");

1 answer

1


Opa, to avoid cast errors you have used Datagridviewcheckboxcell well. Now to fetch the checkbox value you can treat it this way:

bool bChecked = (null != cell && null != cell.Value && true == (bool)cell.Value);

And your result in the code would be this:

private void btnIncluir_Click(object sender, EventArgs e )
 {
     try{

            int cod;
            int qntd;
            DataGridViewCheckBoxCell cell;
            foreach (DataGridViewRow linha in dgvSolicitacaoCliente.Rows)
            {
              cell = linha.Cells["nome da coluna (ou o índice)"] as DataGridViewCheckBoxCell;// linha.Cells["nomeDaColuna"] ou linha.Cells[0]
              bool bChecked = (null != cell && null != cell.Value && true == (bool)cell.Value);
              if (bChecked)
              {
                  cod = Convert.ToInt32(linha.Cells[4].Value.ToString());
                  qntd = Convert.ToInt32(linha.Cells[1].Value.ToString());

                  cmd.CommandText = "insert into solicitacao_item (cod_solicitacao_cliente, cod_produto, qtd) VALUES (@cod_solicitacao_cliente, @cod_produto, @qtd)";
                  cmd.Parameters.Add(new NpgsqlParameter("@cod_solicitacao_cliente", cmd.CommandText = "select MAX(cod_solicliente) from solicitacao_cliente")); 
                  cmd.Parameters.Add(new NpgsqlParameter("@cod_produto", cod));
                  cmd.Parameters.Add(new NpgsqlParameter("@qtd", qntd));

                  cmd.ExecuteNonQuery();
                  conexao.desconecta(cmd.Connection);

               }
            }
            MessageBox.Show("Incluso com sucesso!");
        }
        catch (Exception ex) // Caso de erro, irá mostrar a mensagem de erro!
       {
           MessageBox.Show(ex.ToString()); // mensagem de erro
       }
 }

Browser other questions tagged

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