esponjinha Posted March 17, 2015 at 10:17 PM Report Share #579663 Posted March 17, 2015 at 10:17 PM Boa noite Tenho uma base de dados com uma tabela . Onde tenho um form com uma datagridview e uma text box para insercao de dados . Tenho um botao de adicionar editar e eliminar . Tenho o botao de adicionar a funcionar . O de apagar era para clicar na linha da datagridview e apagar so que ele apaga na datagridview mas na base de dados nao apaga. Ja exprimentei varios codigos de formas diferentes mas nenhuma das formas trabalha. Alguem consegue me ajudar? Obrigado Link to comment Share on other sites More sharing options...
bioshock Posted March 17, 2015 at 10:31 PM Report Share #579665 Posted March 17, 2015 at 10:31 PM Mostra o código que não funciona. Link to comment Share on other sites More sharing options...
thegodfather Posted March 17, 2015 at 11:16 PM Report Share #579669 Posted March 17, 2015 at 11:16 PM Boas, Porque não usas "BindingNavigator"? Cumps! Link to comment Share on other sites More sharing options...
esponjinha Posted March 17, 2015 at 11:34 PM Author Report Share #579671 Posted March 17, 2015 at 11:34 PM este e um dos codigos string sql = "Delete from Marcas where marca= " + dataGridView1.CurrentRow.Cells[0].Value; SqlCommand comando = new SqlCommand(sql, con); con.Open(); int i = comando.ExecuteNonQuery(); if (i > 0) { MessageBox.Show(i + "Dados Excluídos Com Sucesso!!", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information); } con.Close(); Link to comment Share on other sites More sharing options...
bioshock Posted March 18, 2015 at 09:36 AM Report Share #579686 Posted March 18, 2015 at 09:36 AM A MessageBox aparece-te? Link to comment Share on other sites More sharing options...
esponjinha Posted March 18, 2015 at 09:52 PM Author Report Share #579779 Posted March 18, 2015 at 09:52 PM (edited) Tenho outro codigo SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename = C:\Users\Filipe\documents\visual studio 2010\Projects\Vmpa software\Vmpa software\Utilizadores.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); SqlCommand cmd = new SqlCommand (); for (int i = 0; i < dataGridView1.Rows.Count; i++) { DataGridViewRow dr = dataGridView1.Rows[i]; if (dr.Selected == true) { dataGridView1.Rows.RemoveAt(i); try { con.Open(); cmd.CommandText = "Delete from Marca where marca=" + i + ""; cmd.ExecuteNonQuery(); con.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } este apaga da dgv mas nao apaga da bd e da um erro Edited March 19, 2015 at 02:02 PM by apocsantos geshi Link to comment Share on other sites More sharing options...
bioshock Posted March 18, 2015 at 10:23 PM Report Share #579780 Posted March 18, 2015 at 10:23 PM Vou ver se consigo que o Sr. Cavaco Silva me informe qual é o erro que te dá. Link to comment Share on other sites More sharing options...
esponjinha Posted March 19, 2015 at 12:09 AM Author Report Share #579793 Posted March 19, 2015 at 12:09 AM tenho outro codigo for (int i = 0; i < dataGridView1.Rows.Count; i++) { String strConnection = (@"Data Source=.\SQLEXPRESS;AttachDbFilename = C:\Users\Filipe\documents\visual studio 2010\Projects\Vmpa software\Vmpa software\Utilizadores.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); SqlConnection cn = new SqlConnection(strConnection); DataGridViewRow dr = dataGridView1.Rows[i]; if (dr.Selected == true) { dataGridView1.Rows.RemoveAt(i); cmd.CommandText = "Delete from Marcas where marca ='" + i + "'"; cn.Open(); cmd.ExecuteNonQuery(); MessageBox.Show("Deleted"); cn.Close(); } } este da erro na linha cmd.ExecuteNonQuery(); erro: ExecuteNonQuery: Connection property has not been initialized. Link to comment Share on other sites More sharing options...
bioshock Posted March 19, 2015 at 09:29 AM Report Share #579805 Posted March 19, 2015 at 09:29 AM Quando executas a query ele está à espera de uma conexão atribuída e activa no comando e não a estás a atribuir. cmd.Connection = cn; Link to comment Share on other sites More sharing options...
esponjinha Posted March 19, 2015 at 09:29 PM Author Report Share #579864 Posted March 19, 2015 at 09:29 PM agora nao da erro apaga na dgv mas nao na base de dados Link to comment Share on other sites More sharing options...
bioshock Posted March 19, 2015 at 09:56 PM Report Share #579867 Posted March 19, 2015 at 09:56 PM (edited) Porque não existe nada para apagar. A tua query: cmd.CommandText = "Delete from Marcas where marca ='" + i + "'"; Resultado final: DELETE FROM marcas WHERE marca = 1 DELETE FROM marcas WHERE marca = 2 DELETE FROM marcas WHERE marca = 3 O que tu queres é aceder ao índice da DataGridView e devolver o valor. Edited March 19, 2015 at 09:57 PM by bioshock Link to comment Share on other sites More sharing options...
esponjinha Posted March 19, 2015 at 10:10 PM Author Report Share #579870 Posted March 19, 2015 at 10:10 PM entao como faço? Link to comment Share on other sites More sharing options...
bioshock Posted March 19, 2015 at 10:24 PM Report Share #579871 Posted March 19, 2015 at 10:24 PM Atenção ao índice da célula, talvez queiras mudá-lo. string valor = dataGridView1.Rows[i].Cells[0].Value.ToString(); string query = "Delete from Marcas where marca ='" + valor + "'"; Link to comment Share on other sites More sharing options...
esponjinha Posted March 20, 2015 at 12:03 AM Author Report Share #579872 Posted March 20, 2015 at 12:03 AM Agora quando apago apaga sempre o registo aseguir e quando apago o ultimo da erro : Object reference not set to an instance of an object. Link to comment Share on other sites More sharing options...
bioshock Posted March 20, 2015 at 09:18 AM Report Share #579878 Posted March 20, 2015 at 09:18 AM É normal que isso aconteça porque estás a colocar o código que eu te dei depois de dataGridView1.Rows.RemoveAt(i); deves colocar antes. Link to comment Share on other sites More sharing options...
esponjinha Posted March 21, 2015 at 07:02 PM Author Report Share #579953 Posted March 21, 2015 at 07:02 PM Muito obrigado ja funciona perfeitamente. Agora para editar , quero clicar 2 vezes na linha da dgv e aparece os dados na textbox , mas como fasso isso? Link to comment Share on other sites More sharing options...
bioshock Posted March 21, 2015 at 07:25 PM Report Share #579956 Posted March 21, 2015 at 07:25 PM Procura pelo evento CellEndClick (ou algo semelhante) de forma a detectares quando uma célula é editada. Link to comment Share on other sites More sharing options...
esponjinha Posted March 22, 2015 at 09:21 AM Author Report Share #579969 Posted March 22, 2015 at 09:21 AM Ja tenho o codigo na dgv para clicar aparecer o resultado na textbox e no botao fiz o codigo para editar o resultado mas falta -me agora e a parte do update. int selectrows; selectrows = dataGridView1.SelectedRows[0].Index; dataGridView1.Rows[selectrows].SetValues(textBox1.Text); Link to comment Share on other sites More sharing options...
bioshock Posted March 22, 2015 at 11:37 AM Report Share #579970 Posted March 22, 2015 at 11:37 AM É igual ao código que fizeste para inserir, apenas troca a query. Link to comment Share on other sites More sharing options...
esponjinha Posted March 22, 2015 at 07:53 PM Author Report Share #579982 Posted March 22, 2015 at 07:53 PM Ja fiz o codigo mas da me um erro nesta linha cmd.ExecuteNonQuery(); int selectrows; selectrows = dataGridView1.SelectedRows[0].Index; dataGridView1.Rows[selectrows].SetValues(textBox1.Text); System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename = C:\Users\Filipe\documents\visual studio 2010\Projects\Vmpa software\Vmpa software\Utilizadores.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); string marcas = textBox1.Text; System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); cmd.CommandType = System.Data.CommandType.Text; cmd.CommandText = "UPDATE Marcas ( marcas ) VALUES (@marcas)"; cmd.Connection = sqlConnection1; cmd.Parameters.AddWithValue("@marcas", marcas); try { if (textBox1.Text.Trim() == "") { MessageBox.Show("Obrigatorio selecao de dados"); } else { sqlConnection1.Open(); cmd.ExecuteNonQuery(); sqlConnection1.Close(); MessageBox.Show("Dados editados"); textBox1.Text = ""; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now