This is working code, please have a look.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
refreshCurso();
}
SqlConnection con = new SqlConnection(@"Data Source=mymachine\SQLEXPRESS;Initial Catalog=MyTestDB;Integrated Security=True");
DataRow dr;
public void refreshCurso()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from curso", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dt.Rows.InsertAt(dr, 0);
comboBox1.ValueMember = "cod_curso";
comboBox1.DisplayMember = "curso";
comboBox1.DataSource = dt;
}
public void refreshModulo(int cod_curso)
{
con.Open();
SqlCommand cmd = new SqlCommand("select* from modulo where cod_curso = @cod_curso", con);
cmd.Parameters.AddWithValue("cod_curso", cod_curso);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dt.Rows.InsertAt(dr, 0);
comboBox2.ValueMember = "cod_modulo";
comboBox2.DisplayMember = "modulo";
comboBox2.DataSource = dt;
}
public void refreshTurma(int cod_modulo)
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from turma where cod_modulo = @cod_modulo", con);
cmd.Parameters.AddWithValue("cod_modulo", cod_modulo);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dt.Rows.InsertAt(dr, 0);
comboBox3.ValueMember = "cod_turma";
comboBox3.DisplayMember = "turma";
comboBox3.DataSource = dt;
}
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (comboBox1.SelectedValue.ToString() != "")
{
int cod_curso = Convert.ToInt32(comboBox1.SelectedValue.ToString());
refreshModulo(cod_curso);
}
}
private void comboBox2_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (comboBox2.SelectedValue.ToString() != "")
{
int cod_modulo = Convert.ToInt32(comboBox2.SelectedValue.ToString());
refreshTurma(cod_modulo);
}
}
}
}