Cadastro simples SQL 2005 - para estudo
Esse é um dos primeiros softwares para estudo em C# que fiz portanto não leva em consideração muitas boas praticas, é um cadastro bem simples usando SQL Server 2005 Express:
A estrutura do Banco de Dados é a seguinte:
[URL=http://imageshack.us][img:08097f4a94]http://img517.imageshack.us/img517/5751/21266605mw9.jpg[/img:08097f4a94][/URL] [URL=http://g.imageshack.us/img517/21266605mw9.jpg/1/][img:08097f4a94]http://img517.imageshack.us/img517/21266605mw9.jpg/1/w281.png[/img:08097f4a94][/URL]
Código do programa utilizando SQL Parameters:
Principal.cs
Edicao.cs
Cadastro.cs
Baixe o projeto do VS2008 [url=http://rapidshare.com/files/195119353/Atividades.rar]aqui[/url].
Qualquer duvida é só postar. :wink:
A estrutura do Banco de Dados é a seguinte:
[URL=http://imageshack.us][img:08097f4a94]http://img517.imageshack.us/img517/5751/21266605mw9.jpg[/img:08097f4a94][/URL] [URL=http://g.imageshack.us/img517/21266605mw9.jpg/1/][img:08097f4a94]http://img517.imageshack.us/img517/21266605mw9.jpg/1/w281.png[/img:08097f4a94][/URL]
Código do programa utilizando SQL Parameters:
Principal.cs
using System.Data.SqlClient;
namespace Atividades
{
public partial class Principal : Form
{
public Principal()
{
InitializeComponent();
}
private void CarregaDados()
{
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Atividades;");
string sSql = ("SELECT AtividadesID,Nome,Descricao,DataInicio,DataFim FROM Atividades");
SqlCommand cmd = new SqlCommand(sSql, conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sSql, conn);
da.Fill(ds, "Atividades");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Atividades";
try
{
conn.Open();
}
catch (SqlException ex)
{
MessageBox.Show("Erro : " + ex.Message);
}
finally
{
conn.Close();
}
}
private void ExcluiDados()
{
string selecao = dataGridView1.CurrentRow.Cells["AtividadesID"].Value.ToString();
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Atividades;");
string sSql = ("DELETE FROM Atividades WHERE AtividadesID = @AtividadesID");
SqlCommand cmd = new SqlCommand(sSql, conn);
//Parametro
cmd.Parameters.Add("@AtividadesID", SqlDbType.Int);
//Valor Parametro
cmd.Parameters["@AtividadesID"].Value = Convert.ToInt32(selecao);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch(SqlException ex)
{
MessageBox.Show("Erro: " + ex.Message);
}
finally
{
conn.Close();
}
}
private void Principal_Load(object sender, EventArgs e)
{
CarregaDados();
}
private void btnEditar_Click(object sender, EventArgs e)
{
//Recebe valor do ID da linha selecionada
string selecao = dataGridView1.CurrentRow.Cells["AtividadesID"].Value.ToString();
Edicao frm3 = new Edicao();
//Enviar valor para outro form
frm3.mySelection = selecao;
//abrir form de edição
frm3.Show();
}
private void btnNovo_Click(object sender, EventArgs e)
{
Cadastro frm1 = new Cadastro();
frm1.Show();
}
private void btnExcluir_Click(object sender, EventArgs e)
{
ExcluiDados();
CarregaDados();
dataGridView1.Refresh();
}
private void Principal_Activated(object sender, EventArgs e)
{
//Atualizar Grid
CarregaDados();
dataGridView1.Refresh();
}
}
}
Edicao.cs
using System.Data.SqlClient;
namespace Atividades
{
public partial class Edicao : Form
{
public Edicao()
{
InitializeComponent();
}
//Propriedade que recebe linha selecionado do Grid
public string mySelection { get; set; }
private void EditaDados()
{
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Atividades;");
string sSql = "UPDATE Atividades SET Nome=@Nome,Descricao=@Descricao,DataInicio=@DataInicio,DataFim=@DataFim WHERE AtividadesID=@AtividadesID";
SqlCommand cmd = new SqlCommand(sSql, conn);
//Cria Parametros
cmd.Parameters.Add("@Nome",SqlDbType.VarChar, 50);
cmd.Parameters.Add("@Descricao",SqlDbType.VarChar, 50);
cmd.Parameters.Add("@DataInicio",SqlDbType.DateTime);
cmd.Parameters.Add("@DataFim",SqlDbType.DateTime);
cmd.Parameters.Add("@AtividadesID", SqlDbType.Int);
//Valores Parametros
cmd.Parameters["@Nome"].Value = txtNome.Text;
cmd.Parameters["@Descricao"].Value = txtDescricao.Text;
cmd.Parameters["@DataInicio"].Value = txtDataInicio.Text;
cmd.Parameters["@DataFim"].Value = txtDataFim.Text;
cmd.Parameters["@AtividadesID"].Value = Convert.ToInt32(mySelection);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show("Erro: " + ex.Message);
}
finally
{
conn.Close();
}
}
private void Form3_Load(object sender, EventArgs e)
{
int selecaoId = Convert.ToInt32(mySelection);
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Atividades;");
try
{
conn.Open();
string sSql = "SELECT AtividadesID,Nome,Descricao,DataInicio,DataFim FROM Atividades WHERE AtividadesID = ´"+ selecaoId +"´ ";
SqlCommand cmd = new SqlCommand(sSql, conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sSql, conn);
da.Fill(ds,"Atividades");
//Preencher os controles do form
foreach (DataRow dr in ds.Tables["Atividades"].Rows)
{
txtNome.Text = dr["Nome"].ToString();
txtDescricao.Text = dr["Descricao"].ToString();
txtDataInicio.Text = dr["DataInicio"].ToString();
txtDataFim.Text = dr["DataFim"].ToString();
}
}
catch(SqlException ex)
{
MessageBox.Show("Erro: " + ex.Message);
}
finally
{
conn.Close();
}
}
private void btnGravar_Click(object sender, EventArgs e)
{
EditaDados();
}
private void btnCancelar_Click(object sender, EventArgs e)
{
Edicao frm3 = new Edicao();
frm3.Close();
}
}
}
Cadastro.cs
using System.Data.SqlClient;
namespace Atividades
{
public partial class Cadastro : Form
{
public Cadastro()
{
InitializeComponent();
}
private void SalvaDados()
{
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Atividades;");
//Criar comando
string sSql = "INSERT INTO Atividades (Nome,Descricao,DataInicio,DataFim) VALUES (@Nome,@Descricao,@DataInicio,@DataFim)";
SqlCommand cmd = new SqlCommand(sSql, conn);
//Definir Parametros: nome, tipo e tamanho
cmd.Parameters.Add("@Nome", SqlDbType.VarChar, 50);
cmd.Parameters.Add("@Descricao", SqlDbType.VarChar, 50);
cmd.Parameters.Add("@DataInicio", SqlDbType.DateTime);
cmd.Parameters.Add("@DataFim", SqlDbType.DateTime);
//Definir valores dos parametros
cmd.Parameters["@Nome"].Value = txtNome.Text;
cmd.Parameters["@Descricao"].Value = txtDescricao.Text;
cmd.Parameters["@DataInicio"].Value = txtDataInicio.Text;
cmd.Parameters["@DataFim"].Value = txtDataFim.Text;
try
{
conn.Open();
//Executar comando
cmd.ExecuteNonQuery();
//Aviso
MessageBox.Show("Dados gravados com sucesso");
}
catch (SqlException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
finally
{
conn.Close();
}
}
private void btnNovo_Click(object sender, EventArgs e)
{
txtNome.Text = "";
txtDescricao.Text = "";
txtDataInicio.Text = "";
txtDataFim.Text = "";
}
private void btnCadastrar_Click(object sender, EventArgs e)
{
SalvaDados();
}
}
}
Baixe o projeto do VS2008 [url=http://rapidshare.com/files/195119353/Atividades.rar]aqui[/url].
Qualquer duvida é só postar. :wink:
Cjsartorif
Curtidas 0