Unconfigured Ad Widget

Collapse

Anúncio

Collapse
No announcement yet.

Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound

Collapse
This topic is closed.
X
X
 
  • Filter
  • Tempo
  • Show
Clear All
new posts

  • Font Size
    #1

    C# Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound

    Olá,

    Estou com um problema em C#:

    No banco de dados criei a tabela Clientes e listaClientes. Cada cliente é vinculado a uma lista tendo uma chave estrangeira idListaCliente dentro da tablela Clientes.

    Então coloquei um datagridview para atualizar a tabela clientes então ficou assim:


    Código:
                  mAdapter = new SqlCeDataAdapter("SELECT * FROM Clientes WHERE idListasClientes="+ idLista, conn);
    
                    mAdapter.Fill(mDataSet, "Clientes");
    
                    dgvGerenciarClientes.DataSource = mDataSet;
                    
                    dgvGerenciarClientes.DataMember = "Clientes";
    Código:
            private void dgvGerenciarClientes_RowValidated(object sender, DataGridViewCellEventArgs e)
            {
                
                try
                {
                    
                    DataSet changes = ((DataSet)dgvGerenciarClientes.DataSource).GetChanges();
    
                    if (changes != null)
                    {
                        SqlCeCommandBuilder mcb = new SqlCeCommandBuilder(mAdapter);
    
                        mAdapter.UpdateCommand = mcb.GetUpdateCommand();
                        mAdapter.Update(changes, "Clientes");
                        ((DataSet)dgvGerenciarClientes.DataSource).AcceptChanges();
                        
                    }
    
                }
                catch (Exception errRowValidated)
                {
                }
            }
    Ok ate ai tudo bem, mas eu criei uma função para adicionar uma lista de clientes dessa forma:


    Código:
                                    DataRow dt = mDataSet.Tables["Clientes"].NewRow();
                                    for (int i = 0; i < val.Count(); i++)
                                    {
                                        dt[i] = val[i];
                                    }
    
                                    mDataSet.Tables["Clientes"].Rows.Add(dt);
                                    dgvGerenciarClientes.Rows.Add(val);

    Então na linha "dgvGerenciarClientes.Rows.Add(val);" ocorre o seguinte erro:

    Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.

    Então não consigo corrigir isso, alguém sabe como?

  • Font Size
    #2
    Se não me engano, você não pode fazer a conexão automática e depois tentar manipular ele.

    Ou faça tudo por linha de comando, ou automaticamente. - Eu sou adepto a tudo por linha de comando, fica mais rápido e é possível explorar melhor - fazer manipulações.

    Código:
                try
                {
                    SqlConnection conn = new SqlConnection();
                    conn = Conexao.obterConexao();
    
                    SqlCommand cmd = new SqlCommand();
    
                    cmd = new SqlCommand("Select Cod_Cli, Nome, CPF, Endereco, Email, Telefone, Celular, Data_Nasc, Data_Registro from Cliente", conn);
    
                    SqlDataAdapter Result = new SqlDataAdapter(cmd);
                    DataTable Data = new DataTable();
                    Result.Fill(Data);
    
                    if (Data.Rows.Count > 0)
                    {
                        int Count = 0;
                        while (Count < Data.Rows.Count)
                        {
                            dataGridView1.Rows.Add(Data.Rows[Count]["Cod_Cli"].ToString(), Data.Rows[Count]["Nome"].ToString(), Data.Rows[Count]["CPF"], Data.Rows[Count]["Endereco"].ToString(), Data.Rows[Count]["Email"].ToString(), Data.Rows[Count]["Telefone"].ToString(), Data.Rows[Count]["Celular"].ToString(), Data.Rows[Count]["Data_Nasc"], Data.Rows[Count]["Data_Registro"]);
                            Count++;
                        }
                    }
                    Conexao.fecharConexao();
                }
    
                catch (SqlException)
                {
                    MessageBox.Show("Não foi possível se conectar ao banco", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    conn.fecharConexao();
                }
    Qualquer coisa, só falar aí.
    Last edited by Piratica; 25-01-2015, 09:45.
    Se expressarmos gratidão pelo que temos, teremos mais para expressar gratidão... Agradeça!

    Comment


    • Font Size
      #3
      Muito obrigado Piratica, consegui adaptar aqui para funcionar.

      Comment


      • Font Size
        #4
        Postado Originalmente por S4tur0 Ver Post
        Muito obrigado Piratica, consegui adaptar aqui para funcionar.
        As ordens, S4turno. E sempre que tiver tempo, evite usar como controle o data-bound.

        Qualquer coisa, só dar um toque.

        Estrou trancando o tópico, se precisar reabrir ele é só me falar.
        Se expressarmos gratidão pelo que temos, teremos mais para expressar gratidão... Agradeça!

        Comment

        X
        Working...
        X