private void FormLoad_Handler(object sender, EventArgs e) { // Execute SQL query to get Docente rows SqlCommand cmd = new SqlCommand("SELECT * FROM GestaoEscola.GrupoDisciplinar", cn); SqlDataReader reader = cmd.ExecuteReader(); // Create list of Objects given the query results List <GrupoDisciplinar> tuplos = new List <GrupoDisciplinar>(); while (reader.Read()) { GrupoDisciplinar t = new GrupoDisciplinar(); t.num = Int32.Parse(reader["num"].ToString()); t.nome = reader["nome"].ToString(); if (lastId < t.num) { lastId = t.num; } tuplos.Add(t); counter++; } // Close reader reader.Close(); // ObjectListView // Add Objects to list view listObjects.SetObjects(tuplos); // Update stats updateStats(); }
private void criarDisciplina_Click(object sender, EventArgs e) { if (disciplinaNome.Text.Length <= 30) { String commandText = "INSERT INTO GestaoEscola.Disciplina VALUES(1, @nome, @grupo)"; SqlCommand command = new SqlCommand(commandText, cn); // Add vars command.Parameters.Add("@nome", SqlDbType.VarChar); command.Parameters["@nome"].Value = disciplinaNome.Text; command.Parameters.Add("@grupo", SqlDbType.Int); GrupoDisciplinar g = (GrupoDisciplinar)listObjects.SelectedObject; command.Parameters["@grupo"].Value = g.num; // Execute query int rowsAffected = 0; try { rowsAffected = command.ExecuteNonQuery(); Console.WriteLine(String.Format("rowsAffected {0}", rowsAffected)); } catch (SqlException ex) { MessageBox.Show( "Ocorreu um erro, tente novamente!\r\n" + ex.ToString(), "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } // If successful query if (rowsAffected == 2) { MessageBox.Show("Disciplina adicionada ao grupo disciplinar com sucesso!"); } else { MessageBox.Show( "Essa disciplina já existe!", "Erro na submissão!", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } else { MessageBox.Show( "Ocorreu um erro, o tamanho máximo do nome da disciplina é de 30 caracteres!", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); } panelDisc.Visible = false; }
// Methods private void loadGruposDisciplinares() { // Execute SQL query SqlCommand cmd = new SqlCommand("SELECT * FROM GestaoEscola.GrupoDisciplinar;", cn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { GrupoDisciplinar g = new GrupoDisciplinar(); g.num = Int32.Parse(reader["num"].ToString()); g.nome = reader["nome"].ToString(); panelFormFieldGrupoDisciplinar.Items.Add(g.nome); gruposDisciplinares.Add(g); } reader.Close(); }
private void showObject() { // Get Object if (listObjects.Items.Count == 0 | current < 0) { return; } GrupoDisciplinar f = (GrupoDisciplinar)listObjects.SelectedObjects[0]; // Set labels values panelObjectTitulo.Text = "Grupo"; panelObjectSubtitulo.Text = f.nome; // Show panel if (!panelObject.Visible) { panelObject.Visible = true; } panelForm.Visible = false; }
private void editObject() { // Get Object if (listObjects.Items.Count == 0 | current < 0) { return; } GrupoDisciplinar f = (GrupoDisciplinar)listObjects.SelectedObjects[0]; // Set textboxes value panelFormFieldNome.Text = f.nome; // Set title and description panelFormTitulo.Text = "Editar grupo disciplinar"; panelFormDescricao.Text = "Altere os dados e submita o formulário"; panelFormButton.Text = "Submeter"; // Make panel visible if (!panelForm.Visible) { panelForm.Visible = true; } }
public void clone(Docente d) { base.clone(d); // base is same as super in Java this.grupoDisciplinar = d.grupoDisciplinar; }
private void submitForm(Docente docente) { bool edit = (docente != null); // Get form data int nmec = Int32.Parse(panelFormFieldNMec.Text); String nome = panelFormFieldNome.Text; Double salario = Double.Parse(panelFormFieldSalario.Text); int telemovel = Int32.Parse(panelFormFieldContacto.Text); String emailPrefixo = panelFormFieldEmail.Text.Split('@')[0]; String emailDominio = panelFormFieldEmail.Text.Split('@')[1]; GrupoDisciplinar grupoDisciplinar = getGrupoDisciplinar(panelFormFieldGrupoDisciplinar.Text); // Create command String commandText = "pr_Docentes"; SqlCommand command = new SqlCommand(commandText, cn); command.CommandType = CommandType.StoredProcedure; // Add vars command.Parameters.Add("@NMec", SqlDbType.Int); command.Parameters["@NMec"].Value = nmec; command.Parameters.Add("@Nome", SqlDbType.VarChar); command.Parameters["@Nome"].Value = nome; command.Parameters.Add("@Telemovel", SqlDbType.Int); command.Parameters["@Telemovel"].Value = telemovel; command.Parameters.Add("@Email", SqlDbType.VarChar); command.Parameters["@Email"].Value = emailPrefixo; command.Parameters.Add("@EmailDominio", SqlDbType.VarChar); command.Parameters["@EmailDominio"].Value = emailDominio; command.Parameters.Add("@Salario", SqlDbType.Money); command.Parameters["@Salario"].Value = salario; command.Parameters.Add("@GrupoDisciplinar", SqlDbType.Int); command.Parameters["@GrupoDisciplinar"].Value = grupoDisciplinar.num; command.Parameters.Add("@Edit", SqlDbType.Bit); command.Parameters["@Edit"].Value = 0; if (edit) { command.Parameters["@Edit"].Value = 1; } // Return value stuff var returnParameter = command.Parameters.Add("@ReturnVal", SqlDbType.Int); returnParameter.Direction = ParameterDirection.ReturnValue; // Execute query int rowsAffected = 0; int returnValue; try { rowsAffected = command.ExecuteNonQuery(); returnValue = (int)returnParameter.Value; Console.WriteLine(String.Format("rowsAffected {0}", rowsAffected)); } catch (SqlException ex) { String errorMessage = "Ocorreu um erro, verifique que preencheu todos os dados corretamente e tente novamente!"; for (int i = 0; i < ex.Errors.Count; i++) { if (ex.Errors[i].Message.IndexOf("Já existe uma pessoa com o email", StringComparison.OrdinalIgnoreCase) >= 0) { errorMessage = ex.Errors[i].Message; break; } if (ex.Errors[i].Message.IndexOf("Já existe uma pessoa com o número de telemóvel fornecido", StringComparison.OrdinalIgnoreCase) >= 0) { errorMessage = ex.Errors[i].Message; break; } } MessageBox.Show( errorMessage + "\r\n\r\n" + ex.ToString(), "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } // If query is successful if (returnValue == 1) { // If add operation, construct object (was null) if (!edit) { docente = new Docente(); } docente.nmec = nmec; docente.nome = nome; docente.email = emailPrefixo + "@" + emailDominio; docente.telemovel = telemovel; docente.salario = salario; docente.grupoDisciplinar = grupoDisciplinar; if (!edit) { listObjects.AddObject(docente); } // SHow feedback to user String successMessage = "O docente foi adicionado com sucesso!"; if (edit) { successMessage = "O docente foi editado com sucesso"; } MessageBox.Show( successMessage, "Sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information ); // Update objects displayed on interface listObjects.BuildList(true); // Update stats updateStats(); // Hide panels panelForm.Visible = false; panelObject.Visible = false; } else { String messageError = "Ocorreu um erro, verifique que preencheu todos os dados corretamente e tente novamente!"; if (returnValue == -2) { messageError = "Já existe uma pessoa na base de dados com esse número mecanográfico!"; } else if (returnValue == -3 || returnValue == -4) { messageError = "Ocorreu um erro interno na base de dados! Tente novamente."; } MessageBox.Show( messageError, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); } }
private void submitForm(GrupoDisciplinar gd) { /* * If submition for edit t!=null * If new submition t==null */ bool edit = (gd != null); // Get form data String nome = panelFormFieldNome.Text.Trim(); // Create command String commandText = "INSERT INTO GestaoEscola.GrupoDisciplinar VALUES (@ID, @Nome)"; if (edit) { commandText = "UPDATE GestaoEscola.GrupoDisciplinar SET nome = @Nome WHERE num = @ID"; } SqlCommand command = new SqlCommand(commandText, cn); // Add vars command.Parameters.Add("@ID", SqlDbType.Int); if (edit) { command.Parameters["@ID"].Value = gd.num; } else { command.Parameters["@ID"].Value = lastId + 1; } command.Parameters.Add("@Nome", SqlDbType.VarChar, 20); command.Parameters["@Nome"].Value = nome; // Execute query int rowsAffected = 0; try { rowsAffected = command.ExecuteNonQuery(); Console.WriteLine(String.Format("rowsAffected {0}", rowsAffected)); } catch (SqlException ex) { MessageBox.Show( "Ocorreu um erro, verifique que preencheu todos os dados corretamente e tente novamente!\r\n\r\n" + ex.ToString(), "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } // If query is successful if (rowsAffected == 1) { // If add operation if (!edit) { // Update lastId lastId++; // Add tuple to interface list gd = new GrupoDisciplinar(); gd.num = lastId; gd.nome = nome; listObjects.AddObject(gd); } else { // Get object on interface list and change attributes gd.nome = nome; } // SHow feedback to user String successMessage = "O grupo disciplinar foi adicionado com sucesso!"; if (edit) { successMessage = "O grupo disciplinar foi editado com sucesso"; } MessageBox.Show( successMessage, "Sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information ); // Update objects displayed on interface listObjects.BuildList(true); // Update stats updateStats(); // Hide panels panelForm.Visible = false; panelObject.Visible = false; } else { MessageBox.Show( "Ocorreu um erro, verifique que preencheu todos os dados corretamente e tente novamente!", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); } }
private void deleteObject() { // Get Object if (listObjects.Items.Count == 0 | current < 0) { return; } GrupoDisciplinar f = (GrupoDisciplinar)listObjects.SelectedObjects[0]; int itemIndex = listObjects.SelectedIndex; // Confirm delete DialogResult msgb = MessageBox.Show("Tem a certeza que quer eliminar o grupo '" + f.nome + "'?", "Esta operação é irreversível!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); if (msgb == DialogResult.No) { return; } // Create command String commandText = "pr_GruposDisciplinaresDELETE"; SqlCommand command = new SqlCommand(commandText, cn); command.CommandType = CommandType.StoredProcedure; // Add vars command.Parameters.Add("@Codigo", SqlDbType.Int); command.Parameters["@Codigo"].Value = f.num; command.Parameters.Add("@Feedback", SqlDbType.VarChar, 4000).Direction = ParameterDirection.Output; // Return value stuff command.Parameters.Add("@ReturnVal", SqlDbType.Int).Direction = ParameterDirection.ReturnValue; // Execute query int rowsAffected = 0; int returnValue; String returnMessage = ""; try { rowsAffected = command.ExecuteNonQuery(); returnValue = (int)command.Parameters["@ReturnVal"].Value; returnMessage = (String)command.Parameters["@Feedback"].Value; Console.WriteLine(String.Format("rowsAffected {0}", rowsAffected)); } catch (SqlException ex) { MessageBox.Show(ex.GetType().ToString()); MessageBox.Show( "Ocorreu um erro, tente novamente!\r\n\r\n" + ex.ToString(), "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } // If successful query if (rowsAffected == 1 && returnValue == 1) { // Remove object from interface list listObjects.Items.RemoveAt(itemIndex); // Show user feedback MessageBox.Show( "O tuplo foi eliminado com sucesso da base de dados!", "Sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information ); // Update stats updateStats(); // Hide panels panelForm.Visible = false; panelObject.Visible = false; } else { String errorMessage = "Ocorreu um erro, tente novamente!"; if (returnMessage.Contains("conflicted with the REFERENCE constraint \"FK")) { errorMessage = "Este grupo disciplinar não pode ser eliminado enquanto estiver atribuído a um docente!"; } MessageBox.Show( errorMessage + "\r\n\r\n" + returnMessage, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); } }