domingo, 15 de maio de 2011

C# - Consulta SQL com Parâmetros

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;



namespace waAlteraCodigo

{

public partial class Form1 : Form

{

// Variáveis Globais

string StringConexao, Senha;

SqlConnection Conexao;

int ColigadaSelecionada;



public Form1()

{

InitializeComponent();

}



private void ConexaoBD_Open()

{

StringConexao = "Server=;Database=;User ID=;Password=;Trusted_Connection=False";



Conexao = new SqlConnection(StringConexao);



Conexao.Open();

}



private void ConexaoBD_Close()

{

Conexao.Close();

}



private void Form1_Load(object sender, EventArgs e)

{

ConexaoBD_Open();



// Popula Combobox da Coligada

SqlCommand QueryColigada = new SqlCommand("SELECT CODCOLIGADA, NOMEFANTASIA FROM GCOLIGADA ORDER BY CODCOLIGADA", Conexao);



SqlDataReader DadosColigada = QueryColigada.ExecuteReader();



while (DadosColigada.Read())

{

cbboxCol.Items.Add(DadosColigada["CODCOLIGADA"] + " - " + DadosColigada["NOMEFANTASIA"]);

}



ConexaoBD_Close();

}



private void cbboxCol_SelectedIndexChanged(object sender, EventArgs e)

{

ColigadaSelecionada = cbboxCol.SelectedIndex;

}



private void cbboxIdlan_SelectedIndexChanged(object sender, EventArgs e)

{

}



private void cbboxCol_Click(object sender, EventArgs e)

{

}



private void cbboxCol_MouseClick(object sender, MouseEventArgs e)

{

}



private void cbboxIdlan_Click(object sender, EventArgs e)

{

ConexaoBD_Open();



// Popula Combobox do Idlan

SqlCommand QueryIdlan = new SqlCommand("SELECT IDLAN FROM FLAN WHERE CODCOLIGADA = @CODCOLIGADA", Conexao);



QueryIdlan.Parameters.Add(new SqlParameter("@CODCOLIGADA", cbboxCol.SelectedIndex));



SqlDataReader DadosIdlan = QueryIdlan.ExecuteReader();



while (DadosIdlan.Read())

{

cbboxIdlan.Items.Add(DadosIdlan["IDLAN"]);

}



ConexaoBD_Close();



}

}

}