PAGUE 6 MESES
LEVE 12 MESES
GARANTIR DESCONTO

Fórum Como enviar linhas de uma datagridview1 para uma datagridview2 usando checkbox ou outro metodo #576833

12/03/2017

0

C#

Caros bom dia.
Tenho tido alguma dificuldade em passar linhas de uma datagridview1 para datagridview2.
Já tentei varios procedimentos mas sem sucesso.
Estou desenvolvendo uma aplicação em C# windows Form.
Se for caso posso postar o que já tenho feito.
Agradço desde já a vossa atençao.

Abraço
Flávio Reis

Flávio Reis

Responder

Posts

16/03/2017

Flávio Reis

Caros boa tarde!
Como posso introduzir imagens dos formulários da aplicação por forma a entenderem melhor a minha duvida e ajudar da melhor forma a ultrapassa-la.
São dois formulários distintos.
Este é o código que carrega o meu datagridview1.
Este datagridview1 é aberto através do formulário do datagridview2

   private void frmListaEstomProt_Load(object sender, EventArgs e)
        {
            carregaDados();
        }

        private void carregaDados()
     
        {
            db = new BDconexao.accessBD();
            dataGridView1.DataSource = null;
            dataGridView1.Rows.Clear();
            dataGridView1.Refresh();

            string connectionString = db.getConnectionString();
            //string query = "SELECT * FROM   protese UNION (SELECT * FROM tratamento_estomat) ";
            string query = "SELECT id, descricao, codigo, preco_clinica, comparticipacao_perc, comparticipacao_max,comparticipacao_inps,comparticipacao_segurado, total_tratamento   FROM   protese  ";
                 query += "UNION (SELECT id, descricao, codigo, preco_clinica, comparticipacao_perc, comparticipacao_max, comparticipacao_inps,comparticipacao_segurado, total_tratamento FROM tratamento_estomat)";

            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
                {
                    try
                    {
                       //****** crio o meu checkbox no datagrid

                        DataGridViewCheckBoxColumn dgvcCheckBox = new DataGridViewCheckBoxColumn();
                        //dgvcCheckBox.ValueType = typeof(bool);
                        dgvcCheckBox.HeaderText = "Marcar";
                        //dgvcCheckBox.Name = "Marcar";
                        //dgvcCheckBox.ReadOnly = false;
                        dgvcCheckBox.FalseValue = "False";
                        dgvcCheckBox.TrueValue = "True";
                        dataGridView1.Columns.Insert(9, dgvcCheckBox);

                       //******
                       //DataTable dataTable = new DataTable();
                        adapter.Fill(dataTable);
                        
                        for (int i = 0; i < dataTable.Rows.Count; i++)
                        {
                            dataGridView1.Rows.Add(dataTable.Rows[i][0], dataTable.Rows[i][2], dataTable.Rows[i][1], dataTable.Rows[i][3], dataTable.Rows[i][4], dataTable.Rows[i][5], dataTable.Rows[i][6], dataTable.Rows[i][7], dataTable.Rows[i][8]);
                        }
                        dataGridView1.AllowUserToAddRows = false;
                        dataGridView1.AllowUserToDeleteRows = false;
                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show("Error" + ex);
                    }

                }
            }
        }


este é o código do botão que passará as linhas do dagridview1 selecionadas com o checkbox para datagridview2
Não tem erros consigo obter os valores do checkbox, mas nao mostra nada no datagridview2

private void btn_passarDados_Click(object sender, EventArgs e)// this is my button to send the selected lines
        {
            try
              {
                frmTratamentoCopy2 frm = new frmTratamentoCopy2();
                string message = string.Empty;
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    bool rowAlreadyExist = false;
                    bool isSelected = Convert.ToBoolean(row.Cells[9].Value);
					
                    if (isSelected == true)
                    {
                        //// loop to check if the checkbox cell is checked
                        for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
                        {
                            DataGridViewRow row1 = dataGridView1.Rows[i];
                            // the dataGridView2 have one row or more
                            if (frm.dataGridView2.Rows.Count != 0)
                            {
                                // loop to see if the row already exist on dataGridView2
                                for (int j = 0; j <= frm.dataGridView2.Rows.Count - 1; j++)
                                {
                                    if (row1.Cells[0].Value.ToString() == frm.dataGridView2.Rows[j].Cells[0].Value.ToString())
                                    {
                                        rowAlreadyExist = true;
                                        break;
                                    }
                                }
                                // add if the row ont exist on dataGridView2
                                if (rowAlreadyExist == false)
                                {
                                    frm.dataGridView2.Rows.Add(row1.Cells[0].Value.ToString(),
                                                           row1.Cells[1].Value.ToString(),
                                                           row1.Cells[2].Value.ToString()
                                                           //row.Cells[3].Value.ToString(),
                                                           // row.Cells[4].Value.ToString(),
                                                           //  row.Cells[5].Value.ToString(),
                                                           //   row.Cells[6].Value.ToString(),
                                                           //    row.Cells[7].Value.ToString(),
                                                           //     row.Cells[8].Value.ToString()
                                                           );
                                }
                            }
                            // add if the dataGridView2 have no row 
                            else
                            {
                                frm.dataGridView2.Rows.Add(row.Cells[0].Value.ToString(),
                                                           row.Cells[1].Value.ToString(),
                                                           row.Cells[2].Value.ToString()
                                                           //row.Cells[3].Value.ToString(),
                                                           // row.Cells[4].Value.ToString(),
                                                           //  row.Cells[5].Value.ToString(),
                                                           //   row.Cells[6].Value.ToString(),
                                                           //    row.Cells[7].Value.ToString(),
                                                           //     row.Cells[8].Value.ToString()
                                                           );
                            }
                        }
                        //**  verificar os valores que vem no checbox [row.Cells[9].Value.ToString();
]
                        message += Environment.NewLine;
                        message += row.Cells["ID"].Value.ToString();
                        message += Environment.NewLine;
                        message += row.Cells["Codigo"].Value.ToString();
                        message += Environment.NewLine;
                        message += row.Cells[9].Value.ToString();
                        message += Environment.NewLine;
                       
                    }

                }
                MessageBox.Show("Selected Values" + message);
                  }
            catch (Exception ex)
            {
                MessageBox.Show("Error" + ex);
            }

        }


Agradecia muito se pudessem ajudar-me a ultrapassar esse problema.
Obrigado a todos pela vossa atenção
Abraço
Responder

Gostei + 0

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar