//public static void VerifyVoter(VoterInfo VUser, VoterInfo VData) // method to verify voter information //{ // // VUser is the Voter Object retrieved from the Users input from the program // // VData is the Voter Object retrieved from the Database // string VUserString = VUser.ToString(); // string VDataString = VData.ToString(); // if (VUserString == VDataString) // { // // strings match and the voter is correct // } // else // { // // strings don't match, verification failed // } // //} public static Voter RetrieveVoterObject(int VoterID) // should retrieve a Voter Object based on the input of a VoterID, Voter has an override for .ToString() { SqlDataReader DR; Voter VData = new Voter(); string sql = "SELECT * From Voters where VoterID = " + VoterID.ToString(); OpenDB(); SqlCommand cmd = new SqlCommand(sql, con); DR = cmd.ExecuteReader(); if (DR.Read()) { VData.VoterID = (int)DR["VoterID"]; VData.Fname = (string)DR["Fname"]; VData.Lname = (string)DR["Lname"]; VData.HasVoted = (bool)DR["HasVoted"]; // watch this one, might need to specify a 0 or 1 instead of true or false DR.Close(); CloseDB(); return(VData); } else { CloseDB(); throw new Exception($"VoterID {VoterID} Not Found"); } }
//Quando formulario é iniciado é selecionado o ultimo protocolo que foi adicionado no banco private void frm_Cadastro_Load(object sender, EventArgs e) { string pesquisa = "SELECT * FROM TB_PROTOCOLO"; SqlCommand cmd = new SqlCommand(pesquisa, DataBase.obterConexao()); SqlDataReader DR; try { DataBase.obterConexao(); DR = cmd.ExecuteReader(); if (DR.Read()) { lbl_prot_ocult.Text = DR.GetValue(0).ToString(); } else { MessageBox.Show("Erro"); } DR.Close(); cmd.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { DataBase.fecharConexao(); } }
/// <summary> /// 详细信息 /// </summary> /// <param name="TitleListID">题目ID</param> /// <returns></returns> public List <Model.OptionsList> Details(int TitleListID) { string strSql = ""; strSql = "Select * FROM [OptionsList] Where [TitleListID]='" + TitleListID + "'"; List <Model.OptionsList> List = new List <Model.OptionsList>(); SqlParameter[] parameters = { }; SqlDataReader DR; DR = ExamSys.ExecuteReader(strSql.ToString(), parameters); using (DR) { while (DR.Read()) { Model.OptionsList model = new Model.OptionsList(); model.Name = DR["Name"].ToString(); model.T_F = DR["T_F"].ToString(); model.ID = int.Parse(DR["ID"].ToString()); List.Add(model); } DR.Close(); DR.Dispose(); } return(List); }
public int getCusNo(String nic) { Customer_NIC = nic; SqlDataReader DR; try { DataBase db = new DataBase(); con = db.getConnection(); con.Open(); String Sql = "Select Customer_No from Customer where Customer_NIC ='" + Customer_NIC + "'"; SqlCommand cmd = new SqlCommand(Sql, con); DR = cmd.ExecuteReader(); while (DR.Read()) { Customer_No = Convert.ToInt32(DR[0]); } } catch (SqlException) { MessageBox.Show("Please enter the data and try again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(Customer_No); }
public static string[] RetrieveUserRole() { List <string> RoleDescList = new List <string>(); Conn = ConnectDB(); strSQL = "SELECT tblRole.* FROM tblRole ORDER BY tblRole.RoleID"; try { Cmd = new OleDbCommand(); if ((Conn.State == ConnectionState.Closed)) { Conn.Open(); } Cmd.Connection = Conn; Cmd.CommandText = strSQL; DR = Cmd.ExecuteReader(); while (DR.Read()) { //MessageBoxAdv.Show(DR["RoleDescription"].ToString()); RoleDescList.Add(DR["RoleDescription"].ToString()); } } catch (Exception ex) { MessageBoxAdv.Show(ex.Message); } DR.Close(); string[] RoleDesc = RoleDescList.ToArray(); return(RoleDesc); }
private string ConsultaUrl() { string Qry; OleDbDataReader DR; try { Qry = "select top 1 URLdoLinks from URLdoTemplate"; using (DR = DB.DR(Qry)) { if (DR.HasRows == true) { DR.Read(); return DR["URLdoLinks"].ToString().Replace("#", ""); } else { return "erro"; } } } catch (Exception ex) { throw new Exception("ERRO:" + ex.Message + " Classe: Automacao Método: ConsultaUrl"); } }
private void btnRead_Click(object sender, EventArgs e) { string pesquisa = "select * from tbUsuarios where Id= " + txtId.Text; SqlCommand cmd = new SqlCommand(pesquisa, conexao); SqlDataReader DR; try { conexao.Open(); DR = cmd.ExecuteReader(); if (DR.Read()) { txtId.Text = DR.GetValue(0).ToString(); txtLogin.Text = DR.GetValue(1).ToString(); txtSenha.Text = DR.GetValue(2).ToString(); cboPerfil.SelectedText = DR.GetValue(3).ToString(); } else { MessageBox.Show("Usuário e/ou senha inválido(s)"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conexao.Close(); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var modal = Request.QueryString.Get("modal"); bool isModal = !string.IsNullOrEmpty(modal) && modal.Equals("true"); (Master as SiteMaster).BackgroundContent(isModal); } string file = Request.QueryString.Get("Trama"); BasesDatos DB = new BasesDatos(""); DbDataReader DR; string trama = ""; DB = new BasesDatos((Session["IDENTEMI"] != null ? Session["IDENTEMI"].ToString() : "CORE")); DB.Conectar(); DB.CrearComando(@"select trama from Log_Archivos where id_Archivo = @id_Archivo"); DB.AsignarParametroCadena("@id_Archivo", file); DR = DB.EjecutarConsulta(); while (DR.Read()) { trama = DR[0].ToString().Trim(); } DB.Desconectar(); trama = trama.Replace("/r", "\r"); trama = trama.Replace("/n", "\n"); tbTrama.Text = trama; }
/// <summary> /// 显示所有 /// </summary> /// <param name="Type">类型(单选/多选/不定项选/判断)</param> /// <param name="PapersID">试卷ID</param> /// <returns></returns> public List <Model.PapersTitleList> GetList(string Type, int PapersID, int StatusID) { string strSql = ""; //strSql = "Select * FROM [PapersTitleList] Where [Type]='" + Type + "' AND [PapersID]='" + PapersID + "' AND Status_id='"+ StatusID + "' order by newid()"; //add by wangke 2016-12-13 题目排序调整 strSql = "Select * FROM [PapersTitleList] Where [Type]='" + Type + "' AND [PapersID]='" + PapersID + "' AND Status_id='" + StatusID + "' order by ID"; List <Model.PapersTitleList> List = new List <Model.PapersTitleList>(); SqlParameter[] parameters = { }; SqlDataReader DR; DR = ExamSys.ExecuteReader(strSql.ToString(), parameters); using (DR) { while (DR.Read()) { Model.PapersTitleList model = new Model.PapersTitleList(); model.Title = DR["Title"].ToString(); model.T_F = DR["T_F"].ToString(); model.ID = int.Parse(DR["ID"].ToString()); model.Score = int.Parse(DR["Score"].ToString()); List.Add(model); } DR.Close(); DR.Dispose(); } return(List); }
private void btnSave_Click(object sender, EventArgs e) { SqlConnection conexao = new SqlConnection(); conexao.ConnectionString = Properties.Settings.Default.DB_TCM_OutturnConnectionString; conexao.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conexao; cmd.CommandText = "SELECT COD_FUNC FROM TB_TURMA WHERE NOME_TURMA = \'" + cmbNome_Turma.Text + "\';"; cmd.CommandType = CommandType.Text; SqlDataReader DR; DR = cmd.ExecuteReader(); while (DR.Read()) { codigo_func = DR.GetValue(0).ToString(); } conexao.Close(); try { conexao.Open(); using (SqlCommand comando = new SqlCommand("INSERT INTO TB_BOLETIM (COD_ALUNO, COD_FUNC, NOTA_PROVA_ESCRITA_1, NOTA_PROVA_ESCRITA_2, NOTA_PROVA_ESCRITA_3, NOTA_PROVA_ESCRITA_4, NOTA_PROVA_ORAL_1, NOTA_PROVA_ORAL_2, NOTA_PROVA_ORAL_3, NOTA_PROVA_ORAL_4, NOTA_PARTICIPACAO_1, NOTA_PARTICIPACAO_2) VALUES (" + codigo_aluno + ", " + codigo_func + ", " + txtEscrita1_Nota.Text + ", " + txtEscrita2_Nota.Text + ", " + txtEscrita3_Nota.Text + ", " + txtEscrita4_Nota.Text + ", " + txtOral1_Nota.Text + ", " + txtOral2_Nota.Text + ", " + txtOral4_Nota.Text + ", " + txtOral4_Nota.Text + ", " + txtParticipacao1_Nota.Text + ", " + txtParticipacao2_Nota.Text + ");", conexao)) { comando.ExecuteReader(); conexao.Close(); MessageBox.Show("Boletim registrado com sucesso!", "Sucesso!", MessageBoxButtons.OK); ClearScreen(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void btnBuscar_Click(object sender, EventArgs e) { try { /*Conexão com o BD e buscando na tabela usuario*/ MySqlConnection CON = new MySqlConnection("SERVER=localhost;PORT=3306;User ID=root;DATABASE=gestaolocadora;PASSWORD=1234567"); CON.Open(); MySqlCommand CM = new MySqlCommand("SELECT Nome, Telefone, CPF, Email, dataCadastro FROM usuario WHERE Id_Usuario = ?", CON); CM.Parameters.Add("Id_Usuario", MySqlDbType.Int32).Value = txtID.Text; //executa o comando CM.CommandType = CommandType.Text; //recebe o conteúdo que vem do banco MySqlDataReader DR; DR = CM.ExecuteReader(); //insere as informações recebidas do banco para os componentes do form DR.Read(); txtNome.Text = DR.GetString(0); txtTelefone.Text = DR.GetString(1); txtCPF.Text = DR.GetString(2); txtEmail.Text = DR.GetString(3); dataCadastro.Text = DR.GetString(4); } catch (Exception ex) { MessageBox.Show("ID não encontrado!"); } }
private void btnBuscar_Click(object sender, EventArgs e) { try { /*Conexão com o BD e buscando na tabela filmes*/ MySqlConnection CON = new MySqlConnection("SERVER=localhost;PORT=3306;User ID=root;DATABASE=gestaolocadora;PASSWORD=1234567"); CON.Open(); MySqlCommand CM = new MySqlCommand("SELECT Titulo, Produtora, Descricao, NotaFilme, DataLancamento, Categoria, ValorFilme FROM filme WHERE Id_Filme = ?", CON); CM.Parameters.Add("Id_Filme", MySqlDbType.Int32).Value = txtIDFilme.Text; //executa o comando CM.CommandType = CommandType.Text; //recebe o conteúdo que vem do banco MySqlDataReader DR; DR = CM.ExecuteReader(); //insere as informações recebidas do banco para os componentes do form DR.Read(); txtTituloFilme.Text = DR.GetString(0); txtProdutora.Text = DR.GetString(1); txtDescricao.Text = DR.GetString(2); txtNotaFilme.Text = DR.GetString(3); txtLancamento.Text = DR.GetString(4); txtCategoria.Text = DR.GetString(5); txtValorFilme.Text = DR.GetString(6); } catch (Exception ex) { MessageBox.Show("ID não encontrado!"); } }
public static VoterInfo RetrieveVoterInfoObject(int VoterID) // should retrieve a Candidate Object based on the input of a CandidateID, Candidate has an override for .ToString() { SqlDataReader DR; VoterInfo VIData = new VoterInfo(); string sql = "SELECT * From VoterInfo where VoterID = " + VoterID.ToString(); OpenDB(); SqlCommand cmd = new SqlCommand(sql, con); DR = cmd.ExecuteReader(); if (DR.Read()) { VIData.VoterID = (int)DR["VoterID"]; VIData.Salt = (byte[])DR["Salt"]; VIData.Hash = (byte[])DR["Hash"]; DR.Close(); CloseDB(); return(VIData); } else { CloseDB(); throw new Exception($"VoterID {VoterID} Not Found"); } }
public static Candidate RetrieveCandidateObject(int CandidateID) // should retrieve a Candidate Object based on the input of a CandidateID, Candidate has an override for .ToString() { SqlDataReader DR; Candidate CData = new Candidate(); string sql = "SELECT * From Candidates where VoterID = " + CandidateID.ToString(); OpenDB(); SqlCommand cmd = new SqlCommand(sql, con); DR = cmd.ExecuteReader(); if (DR.Read()) { CData.CandidateID = (int)DR["CandidateID"]; CData.FName = (string)DR["Fname"]; CData.LName = (string)DR["Lname"]; CData.PartyName = (string)DR["PartyName"]; CData.Seat = (string)DR["Seat"]; CData.VoteCount = (int)DR["VoteCount"]; DR.Close(); CloseDB(); return(CData); } else { CloseDB(); throw new Exception($"VoterID {CandidateID} Not Found"); } }
/// <summary> /// 显示所有 /// </summary> /// <param name="TitleListID">题目ID</param> /// <returns></returns> public List <Model.PapersOptionsList> GetList(int TitleListID, int PapersID) { string strSql = ""; //strSql = "Select * FROM [PapersOptionsList] Where [TitleListID]='" + TitleListID + "' and [PapersID]='" + PapersID + "' order by newid()"; strSql = "Select * FROM [PapersOptionsList] Where [TitleListID]='" + TitleListID + "' and [PapersID]='" + PapersID + "' order by ID"; List <Model.PapersOptionsList> List = new List <Model.PapersOptionsList>(); SqlParameter[] parameters = { }; SqlDataReader DR; DR = ExamSys.ExecuteReader(strSql.ToString(), parameters); using (DR) { while (DR.Read()) { Model.PapersOptionsList model = new Model.PapersOptionsList(); model.Name = DR["Name"].ToString(); model.T_F = DR["T_F"].ToString(); model.PapersID = int.Parse(DR["PapersID"].ToString()); model.TitleListID = int.Parse(DR["TitleListID"].ToString()); model.ID = int.Parse(DR["ID"].ToString()); model.Score = int.Parse(DR["Score"].ToString()); List.Add(model); } DR.Close(); DR.Dispose(); } return(List); }
public IList <TarefaDTO> CarregarDadosCmbVersao() { try { SqlConnection connection = new SqlConnection(); connection.ConnectionString = Properties.Settings.Default.CST; SqlCommand command = new SqlCommand(); command.CommandType = System.Data.CommandType.Text; command.CommandText = "SELECT DISTINCT versao FROM TAREFA"; command.Connection = connection; SqlDataReader DR; IList <TarefaDTO> listTarefaDTO = new List <TarefaDTO>(); connection.Open(); DR = command.ExecuteReader(); if (DR.HasRows) { while (DR.Read()) { TarefaDTO TAREFA = new TarefaDTO(); TAREFA.Versao = Convert.ToString(DR["versao"]); listTarefaDTO.Add(TAREFA); } } return(listTarefaDTO); } catch (Exception ex) { throw ex; } }
/// <summary> /// 详细信息 /// </summary> /// <param name="ID">ID</param> /// <returns></returns> public List <Model.Papers> Details(int ID) { string strSql = ""; strSql = "Select * FROM [Papers] Where [ID]='" + ID + "'"; List <Model.Papers> List = new List <Model.Papers>(); SqlParameter[] parameters = { }; SqlDataReader DR; DR = ExamSys.ExecuteReader(strSql.ToString(), parameters); using (DR) { while (DR.Read()) { Model.Papers model = new Model.Papers(); model.ID = int.Parse(DR["ID"].ToString()); model.Name = DR["Name"].ToString(); model.CourseID = int.Parse(DR["CourseID"].ToString()); model.Type = DR["Type"].ToString(); model.Lock = int.Parse(DR["Lock"].ToString()); List.Add(model); } DR.Close(); DR.Dispose(); } return(List); }
private void RefreshBookList() { try { SqlConnection conn = new SqlConnection(this.ConnStr.Trim()); SqlCommand cmd = new SqlCommand("select * from BookLocation", conn); SqlDataReader DR; ListViewItem lvi; int i = 0; viewProducts.Items.Clear(); conn.Open(); DR = cmd.ExecuteReader(); while (DR.Read()) { lvi = new ListViewItem(DR["BookLocationId"].ToString()); lvi.Tag = DR["BookLocationId"].ToString(); lvi.SubItems.Add(DR["BookLocationInfo"].ToString()); lvi.SubItems.Add(DR["BookRoomInfo"].ToString()); viewProducts.Items.Add(lvi); i = i + 1; } conn.Close(); lblTotel.Text = i.ToString(); } catch {} //listViewitem }
private void btnPesquisar_Click(object sender, EventArgs e) { //instrução sql responsável por pesquisar o banco de dados (CRUD - Read) string pesquisa = "select * from tbContatos where idContatos = " + txbId.Text; SqlCommand cmd = new SqlCommand(pesquisa, conexao); //objeto responsável pelos comandos(querys) no sql. //criando objeto de nome cmd tendo como modelo a classe OleDbCommand para execultar a instução sql // OleDbCommand cmd = new OleDbCommand(pesquisa, conexao); // Atravé da classe OleDbDataReader que faz parte do SqlCliente, criamos uma //variável chamada DR que será usada na leitura dos dados (instrução select) SqlDataReader DR; //OleDbDataReader DR; //tratamento de exeções: try - catch - finally (em caso de erro de erro capturamos o erro) try { //abrindo conexão com o bando de dados conexao.Open(); cmd.ExecuteNonQuery(); //Executa o cmd e pega todos os dados que buscamos com o nosso comando DataSet ds = new DataSet(); //setar dados SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; //adapta o cmd ao projeto da.Fill(ds); // preenche todas as informações dentro do DataSet //executando a instrução e armazenando o resultado do reader DR DR = cmd.ExecuteReader(); if (DR.Read()) { txbId.Text = DR.GetValue(0).ToString(); txbNome.Text = DR.GetValue(1).ToString(); txbTelefone.Text = DR.GetValue(2).ToString(); txbEmail.Text = DR.GetValue(3).ToString(); } //Exibe as Informações nas caisas de texto(textBox) correspondente (#) //nova pesquisa else { MessageBox.Show("Registro não encontrado"); txbNome.Text = ""; txbTelefone.Text = ""; txbEmail.Text = ""; txbId.Focus(); } //encerrando o uso do Reader DR DR.Close(); //encerra o cmd cmd.Dispose(); } catch (Exception ex) { //exibe o erro MessageBox.Show(ex.Message); } // de qualquer forma sempre fechar a conexão com o banco ("lembrar da porta da //geladeira rsrsrs") finally { conexao.Close(); } }
protected void ddNamaPerusahaan_SelectedIndexChanged(object sender, EventArgs e) { try { //DropDownList ddNamaPerusahaan = (DropDownList)GridResult.Rows[e.NewEditIndex].FindControl("ddNamaPerusahaan"); //DropDownList ddNamaBarang = (DropDownList)GridResult.Rows[e.NewEditIndex].FindControl("ddNamaBarang"); using (SqlConnection con = new SqlConnection(strConString)) { SqlCommand cmd = new SqlCommand("Select * From tblPerusahaan Where [Nama Perusahaan] = '" + ddNamaPerusahaan.SelectedValue + "'", con); con.Open(); cmd.ExecuteNonQuery(); SqlDataReader DR; DR = cmd.ExecuteReader(); while (DR.Read()) { //string IdPerusahaan = (string)DR["IdPerusahaan"].ToString(); lblIdPerusahaan.Text = DR[0].ToString(); } DR.Close(); con.Close(); } } catch (Exception ex) { message = ex.Message; } }
public List <FuncionalidadeDTO> ConsultaFuncionalidade() { try { SqlConnection sqlCon = new SqlConnection(); sqlCon.ConnectionString = Properties.Settings.Default.CST; SqlCommand CM = new SqlCommand(); CM.CommandType = System.Data.CommandType.Text; CM.CommandText = "SELECT * FROM Funcionalidade;"; CM.Connection = sqlCon; SqlDataReader DR; List <FuncionalidadeDTO> listFuncionalidadeDTO = new List <FuncionalidadeDTO>(); sqlCon.Open(); DR = CM.ExecuteReader(); if (DR.HasRows) { while (DR.Read()) { FuncionalidadeDTO func = new FuncionalidadeDTO(); func.Id_Funcionalidade = Convert.ToInt32(DR["Id_Funcionalidade"]); func.Funcionalidade = Convert.ToString(DR["Funcionalidade"]); func.Campo = Convert.ToString(DR["Campo"]); listFuncionalidadeDTO.Add(func); } } return(listFuncionalidadeDTO); } catch (Exception ex) { throw ex; } }
/// <summary> /// 详细信息 /// </summary> /// <param name="ID">ID</param> /// <returns></returns> public List <Model.TitleList> Details(int ID) { string strSql = ""; strSql = "Select * FROM [TitleList] Where [ID]='" + ID + "'"; List <Model.TitleList> List = new List <Model.TitleList>(); SqlParameter[] parameters = { }; SqlDataReader DR; DR = ExamSys.ExecuteReader(strSql.ToString(), parameters); using (DR) { while (DR.Read()) { Model.TitleList model = new Model.TitleList(); model.Title = DR["Title"].ToString(); model.T_F = DR["T_F"].ToString(); model.Analysis = DR["Analysis"].ToString(); model.ID = int.Parse(DR["ID"].ToString()); model.CourseID = int.Parse(DR["CourseID"].ToString()); model.Status_id = int.Parse(DR["Status_id"].ToString()); List.Add(model); } DR.Close(); DR.Dispose(); } return(List); }
public bool consultar(object objeto) { bool sucesso = false; Aluno aluno = new Aluno(); aluno = (Aluno)objeto; string SELECT = "SELECT * FROM Alunos WHERE idAluno = " + aluno.Id; SqlConnection conn = ConexaoBancoDados.obterConexao(); try { SqlCommand cmd = new SqlCommand(SELECT, conn); SqlDataReader DR; DR = cmd.ExecuteReader(); if (DR.Read()) { aluno.Id = Convert.ToInt32(DR["idAluno"].ToString()); aluno.Nome = DR["nome"].ToString(); aluno.PaisOrigem = DR["paisOrigem"].ToString(); aluno.Idade = Convert.ToInt32(DR["idade"].ToString()); } } catch (SqlException ex) { Console.WriteLine("Erro de Inserção:" + ex); } finally { ConexaoBancoDados.fecharConexao(); } return sucesso; }
/// <summary> /// 显示所有 /// </summary> /// <param name="Type">类型(单选/多选/不定项选/判断)</param> /// <param name="CourseID">课程ID</param> /// <param name="Extent">程度</param> /// <returns></returns> public List <Model.TitleList> GetList(string Type, int CourseID, string Extent) { string strSql = ""; strSql = "Select * FROM [TitleList] Where [Type]='" + Type + "' AND [CourseID]='" + CourseID + "' AND [Extent]='" + Extent + "'"; List <Model.TitleList> List = new List <Model.TitleList>(); SqlParameter[] parameters = { }; SqlDataReader DR; DR = ExamSys.ExecuteReader(strSql.ToString(), parameters); using (DR) { while (DR.Read()) { Model.TitleList model = new Model.TitleList(); model.Title = DR["Title"].ToString(); model.T_F = DR["T_F"].ToString(); model.Analysis = DR["Analysis"].ToString(); model.ID = int.Parse(DR["ID"].ToString()); model.Extent = DR["Extent"].ToString(); List.Add(model); } DR.Close(); DR.Dispose(); } return(List); }
private static Boolean checkExistUser(string username, string teacherID) { // the query: string strSQL = " SELECT tblUser.Username, tblTeacher.TeacherID " + " FROM tblTeacher INNER JOIN tblUser ON tblTeacher.TeacherID = tblUser.TeacherID " + " WHERE tblUser.Username = '******' Or tblTeacher.TeacherID = " + teacherID; if ((Conn.State == ConnectionState.Closed)) { Conn.Open(); } Cmd = new OleDbCommand(strSQL, Conn); DR = Cmd.ExecuteReader(); Boolean userFound = false; while (DR.Read()) { userFound = true; } // checking the result if ((userFound == true)) { MessageBoxAdv.Show("พบผู้ใช้ในระบบ!", "ผิดพลาด", MessageBoxButtons.OK, MessageBoxIcon.Error); } Conn.Close(); return(userFound); }
//Quando formulario é iniciado é selecionado o ultimo protocolo que foi adicionado no banco //Quando formulário é iniciado seleciona o usuario logado private void frm_Serviços_Load(object sender, EventArgs e) { //PROTOCOLO string pesquisa = "SELECT * FROM TB_PROTOCOLO"; SqlCommand cmd = new SqlCommand(pesquisa, DataBase.obterConexao()); SqlDataReader DR; try { DataBase.obterConexao(); DR = cmd.ExecuteReader(); if (DR.Read()) { lbl_prot_ocult.Text = DR.GetValue(0).ToString(); } else { MessageBox.Show("Erro para pegar o valor do protocolo", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } DR.Close(); cmd.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { DataBase.fecharConexao(); } //USUARIO string pesq = "SELECT * FROM TB_DADOS_LOG"; SqlCommand cmd2 = new SqlCommand(pesq, DataBase.obterConexao()); SqlDataReader DR2; try { DataBase.obterConexao(); DR2 = cmd2.ExecuteReader(); if (DR2.Read()) { txt_rg_func.Text = DR2.GetValue(2).ToString(); lbl_exp_nome_func.Text = DR2.GetValue(0).ToString(); lbl_exp_sbrnome_func.Text = DR2.GetValue(1).ToString(); } DR2.Close(); cmd2.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { DataBase.fecharConexao(); } }
private void frm_alterafunc_Load(object sender, EventArgs e) { string pesq = "SELECT * FROM TB_DADOS_LOG"; SqlCommand cmd = new SqlCommand(pesq, DataBase.obterConexao()); SqlDataReader DR; try { DataBase.obterConexao(); DR = cmd.ExecuteReader(); if (DR.Read()) { txt_pesquisa.Text = DR.GetValue(2).ToString(); } DR.Close(); cmd.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { DataBase.fecharConexao(); } }
private void btnBuscar_Click(object sender, EventArgs e) { string read = "SELECT (SELECT SUM(Monto) FROM Ingresos WHERE Empleado='" + this.cbxEmpleado.Text + "') - (SELECT SUM(Monto) FROM Deducciones WHERE Empleado='" + this.cbxEmpleado.Text + "')"; SqlCommand cmd = new SqlCommand(read, conexao); SqlDataReader DR; try { conexao.Open(); DR = cmd.ExecuteReader(); if (DR.Read()) { txtSalario.Text = DR.GetValue(0).ToString(); } else { MessageBox.Show("Registro no encontrado."); txtSalario.Clear(); cbxEmpleado.Focus(); } DR.Close(); cmd.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conexao.Close(); } }
/* * Edit es para realizar una update, aunque la update se lleva a cabo en la funciones Save * , Edit solo regresa la informacion de la base de datos a cada uno de los campos correspondenties para la vista * que es EditAnciano */ public IActionResult Edit(string Id) { SqlCommand com = new SqlCommand("Select * from Marcas where Ma_Id=" + Id, connection);//Se busca el id de acuerdo al registro en la base de datos SqlDataReader DR; Anciano row = new Anciano { An_Id = 0, An_primerNombre = "", An_segundoNombre = "", An_primerApellido = "", An_segundoApellido = "", An_relacion = "", /*An_fechaNacimiento = 0, Estoy investigando como guardar un tipo date*/ An_valMinNormal = 0, An_valMaxNormal = 0, An_valMinIrregular = 0, An_valMaxIrregular = 0 }; connection.Open(); DR = com.ExecuteReader(); if (DR.Read()) { //relacion entre el campo y el registro para regresar los datos row = new Anciano { An_Id = Convert.ToInt32(DR["An_Id"]), An_primerNombre = DR["An_primerNombre"].ToString(), An_segundoNombre = DR["An_segundoNombre"].ToString(), An_primerApellido = DR["An_primerApellido"].ToString(), An_segundoApellido = DR["An_segundoApellido"].ToString(), An_fechaNacimiento = Convert.ToDateTime(DR["An_fechaNacimiento"]), An_relacion = DR["An_relacion"].ToString(), An_valMinNormal = Convert.ToInt32(DR["An_valMinNormal"]), An_valMaxNormal = Convert.ToInt32(DR["An_valMaxNormal"]), An_valMinIrregular = Convert.ToInt32(DR["An_valMinIrregular"]), An_valMaxIrregular = Convert.ToInt32(DR["An_valMaxIrregular"]) }; } connection.Close(); return(View(row)); }
public List <string> GetAvailableColors() { List <string> availableColors = new List <string>(); SqlConnection CapstoneColors = new SqlConnection(); CapstoneColors.ConnectionString = @"Persist Security Info=False;Integrated Security=True;Database=CentreHigh3DPrintingServicesDB;Server=DATABAIST;"; CapstoneColors.Open(); SqlCommand Command = new SqlCommand { Connection = CapstoneColors, CommandType = CommandType.StoredProcedure, CommandText = "GetAvailableColors" }; SqlDataReader DR; DR = Command.ExecuteReader(); if (DR.HasRows) { while (DR.Read()) { for (int i = 0; i < DR.FieldCount; i++) { availableColors.Add(DR[i].ToString()); } } } DR.Close(); CapstoneColors.Close(); return(availableColors); }