protected void btnSalvar_Click(object sender, EventArgs e) { try { var antigaListaDeCentrosDeCusto = Controller.BuscarTodosOsCentrosDeCustoDeUmDepartamento(int.Parse(Session["DepartamentoLogadoId"].ToString())); Hospital hospital; if (FuncaoDaPagina == "a") { hospital = Controller.BuscarHospitalPor(int.Parse(ddlHospitais.SelectedValue)); hospital.Nome = txtNome.Text; } else { hospital = new Hospital(); hospital.Nome = txtNome.Text; } foreach (RepeaterItem item in rptCentrosDeCusto.Items) { if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) { if (((CheckBox)item.FindControl("chkSelecionado")).Checked) { int centroDeCustoId = int.Parse(((HiddenField)item.FindControl("hdnIdSetor")).Value); if (!hospital.CentrosDeCusto.Any(c => c.Id == centroDeCustoId)) hospital.Adicionar(controller.ObterCentroDeCustoPor(centroDeCustoId: centroDeCustoId)); } else { int centroDeCustoId = int.Parse(((HiddenField)item.FindControl("hdnIdSetor")).Value); if (hospital.CentrosDeCusto.Any(c => c.Id == centroDeCustoId)) { if (hospital.Id > 0) { var nome = ((HiddenField)item.FindControl("hdnNomeSetor")).Value; Orcamentos orcamentos = new Orcamentos(); var orcamentosDeViagem = orcamentos.TodosOrcamentosDeViagemPor(hospital.CentrosDeCusto.Where(c => c.Id == centroDeCustoId).FirstOrDefault(), hospital); var orcamentosOperacionais = orcamentos.TodosOrcamentosOperacionaisPor(hospital.CentrosDeCusto.Where(c => c.Id == centroDeCustoId).FirstOrDefault(), hospital); var funcionarios = hospital.CentrosDeCusto.Where(c => c.Id == centroDeCustoId).FirstOrDefault().Funcionarios.Where(d => d.Departamento == hospital); if (orcamentosDeViagem != null && orcamentosDeViagem.Count > 0) throw new Exception("Não é possivel Retirar o Centro de Custo:" + nome + " pois ele está atrelado a pelomenos um Orcamento de viagem."); if (orcamentosOperacionais != null && orcamentosOperacionais.Count > 0) throw new Exception("Não é possivel Retirar o Centro de Custo:" + nome + " pois ele está atrelado a pelomenos um Orcamento de despesa operacional."); if (funcionarios != null && funcionarios.Count() > 0) throw new Exception("Não é possivel Retirar o Centro de Custo:" + nome + " pois ele está atrelado a pelomenos um funcionário com este Departamento."); } hospital.CentrosDeCusto.Remove(hospital.CentrosDeCusto.Where(c => c.Id == centroDeCustoId).FirstOrDefault()); } } } } Controller.SalvarDepartamento(hospital); Notificacao = "Hospital salvo com sucesso"; } catch (Exception ex) { Notificacao = ex.Message; } EnviarMensagem(); LimparCampos(); PopularRepeaterDeCentrosDeCusto(); }