Conexao com banco em C#
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=SEUBANCO;User ID=sa");
SqlCommand sqlComandoo = new SqlCommand("select * from TABELADOBANCO", con);
SqlDataAdapter dadapter = new SqlDataAdapter();
dadapter.SelectCommand = sqlComandoo;
DataTable dtable = new DataTable();
dadapter.Fill(dtable);
SEUDATAGRIDVIEW.DataSource = dtable;
con.Close()
Algumas dúvidas com relação a conexão com banco SQL em C#
Instanciar a classe responsável pela conexão e se preferir já pode colocar a string junto com o instanciamento e abrir a conexao:
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=SEUBANCO;User ID=sa");
Con.Open();
Instanciar o comando SQL juntamente com a conexao ja feita:
SqlCommand sqlcom = new SqlCommand("Select * from tab_TABELA_DO_BANCO", con);
Instanciar o DataAdapter:
SqlDataAdapter adp = new SqlDataAdapter();
Preencher o DataAdapter com o comando SQL executado:
adp.SelectCommand = sqlcom;
Se vai usar um DataGridView vc deve instanciar um DataTable()
DataTable dt = new DataTable();
Use o Método Fill para preencher o DataTable com o DataAdapter usando o método Fill();
adp.Fill(dt);
Preencha o dataGridView com o DataTable()
SEUDATAGRIDVIEW.DataSource = dt;
Nunca esqueça de fechar a conexão:
con.Close();
Uma opção muito útil fazer com que a coluna selecionada no gridView traga as informações para os TextBox Qdo selecionado.
Para isso:
Mude a propriedade SelectionMode para FULLROWSELECT
Dê Duplo Clique no Evento do DataGridView e coloque o código abaixo:
SEUDATAGRIDVIEW.SelectedRows[0].Cells[0].Value.ToString()
SEUDATAGRIDVIEW.SelectedRows[0].Cells[1].Value.ToString()
Para jogar para o TextBox vc deverá converter antes de jogar:
txtCod.Text = (Convert.ToString(SEUDATAGRIDVIEW.SelectedRows[0].Cells[0].Value.ToString()));
txtNome.Text = (Convert.ToString(SEUDATAGRIDVIEW.SelectedRows[0].Cells[1].Value.ToString()));
Dessa forma ao clicar no grid vc enviará as informações para o TextBox que deseja.
Alguns exemplos para gravar no banco:
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=SEUBANCO2000;User ID=sa");
SqlCommand sqlcom = new SqlCommand("insert into TABELA_DO_BANCO(nome, endereco, cidade, tel_res, tel_cel, email) Values(" + "'" + txtNome.Text + "'" + "," + "'" + txtEndereco.Text + "'" + "," + "'" + txtCidade.Text + "'" + "," + "'" + txtTelRes.Text + "'" + "," + "'" + txtTelCel.Text + "'" + "," + "'" + TxtEmail.Text + "'" + ")", con);
con.Open();
sqlcom.ExecuteNonQuery();
con.Close();
PopulaGrid();
Para dar update no banco:
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=SEUBANCO2000;User ID=sa");
SqlCommand sqlcom = new SqlCommand("update TABELA_DO_BANCO set nome = " + "'" + txtNome.Text + "'" + "," + "endereco = " + "'" + txtEndereco.Text + "'" + "," + "cidade = " + "'" + txtCidade.Text + "'" + "," + " tel_res = " + "'" + txtTelRes.Text + "'" + "," + "tel_cel = " + "'" + txtTelCel.Text + "'" + "," + " email = " + "'" + TxtEmail.Text + "'" + "where cod_usuario = " + txtCod.Text, con);
con.Open();
sqlcom.ExecuteNonQuery();
con.Close();
PopulaGrid();
Para deletar do banco:
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=SEUBANCO2000;User ID=sa");
SqlCommand sqlcom = new SqlCommand("Delete from TABELA_DO_BANCO where cod_usuario = " + txtCod.Text, con);
con.Open();
sqlcom.ExecuteNonQuery();
con.Close();
PopulaGrid();
e para pesquisar usando o Like:
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=SEUBANCO2000;User ID=sa");
SqlCommand sqlComandoo = new SqlCommand("select * from TABELA_DO_BANCO where nome like " + "'" + "%" + txtPesquisa.Text + "%" + "'", con);
SqlDataAdapter dadapter = new SqlDataAdapter();
dadapter.SelectCommand = sqlComandoo;
DataTable dtable = new DataTable();
dadapter.Fill(dtable);
SEUDATAGRIDVIEW.DataSource = dtable;
con.Close();
----------------------------------------------------
Array com leitura de TXT
namespace new_save
{
public partial class Form1 : Form
{
string[] aServicos = new string[250];
string[] aServidores = new string[250];
int i = 0;
ServiceController servicor = new ServiceController();
string aew;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
populaRadio();
}
public void populaRadio()
{
i = 0;
rtMensagens.Clear();
//StreamReader leLog = new StreamReader(@"c:/TEMP/logfsm.TXT");
// while (!leLog.EndOfStream)
// {
// rtMensagens.Text = leLog.ReadToEnd();
// }
// leLog.Close();
StreamReader leTxtServicos = new StreamReader(@"c:/TEMP/SERVERS.TXT");
int altura = 25;
while (!leTxtServicos.EndOfStream)
{
string registro = leTxtServicos.ReadLine();
aServidores[i] = registro.Substring(0, 10).Trim();
aServicos[i] = registro.Substring(16, 28).Trim();
dtgservidores.Rows.Add(aServidores[i], aServicos[i]);
try
{
ServiceController servicow = new ServiceController(aServicos[i], aServidores[i]);
aew = servicow.Status.ToString().Trim();
RadioButton rb = new RadioButton()
{
Text = aServidores[i] + " -- " + aServicos[i] + " -- " + "(" + aew + ")",
Location = new Point(10, altura),
Width = groupBox1.Width - 30
};
altura += 25;
groupBox1.Controls.Add(rb);
aew = servicow.Status.ToString().Trim();
if (servicow.Status.ToString() != "Running")
{
rb.Enabled = false;
}
}
catch (Exception erros)
{
int linha = i + 1;
string erro2 = ("Atenção --> " + (aServidores[i]) + " <-- ou o serviço --> " + aServicos[i] +
"<--- erro na linha " + linha + " do arq TXT em c:\\temp\\servers.txt");
toolStripStatusLabel1.Text = erro2;
StreamWriter gravalog = new StreamWriter(@"c:/TEMP/logfsm.TXT");
gravalog.WriteLine(erros.Message + erro2 + "--------------------------------------------------");
gravalog.Close();
i--;
}
i++;
}
altura += 10;
groupBox1.Height = altura;
groupBox1.Text = "Selecione o serviço a ser Reiniciado";
leTxtServicos.Close();
}
private void button1_Click(object sender, EventArgs e)
{
foreach (Control rb in groupBox1.Controls)
{
RadioButton r = (RadioButton)rb;
if (r.Checked)
{
button1.Text = "Processando - AGUARDE";
ServiceController service = new ServiceController(aServicos[r.TabIndex], aServidores[r.TabIndex]);
r.Text = ("PARANDO o serviço " + aServicos[r.TabIndex]);
r.Enabled = false;
string status_incial = aew;
try
{
service.Stop();
}
catch (Exception)
{
MessageBox.Show("erro - Vc nao tem permissão para alterar o estado de um serviço nesse Servidor");
}
aew = service.Status.ToString();
while (aew != "Stopped")
{
button1.Enabled = false;
aew = service.Status.ToString();
rtMensagens.AppendText("..");
rtMensagens.AppendText("........");
rtMensagens.AppendText("...........");
rtMensagens.AppendText("................." + "\n");
rtMensagens.AppendText("......................." + "\n");
rtMensagens.AppendText("................................." + "\n");
rtMensagens.AppendText("............................................." + "\n");
r.Text = ("STARTANDO o serviço");
service.Refresh();
}
//rtMensagens.Text = (service.Status.ToString() + " com sucesso" + " " + aServidores[r.TabIndex] + " " + aServicos[r.TabIndex]);
r.Enabled = false;
r.Checked = false;
service.Start();
i = 0;
while (aew != "Running")
{
aew = service.Status.ToString();
rtMensagens.AppendText(".." + "\n");
rtMensagens.AppendText("........" + "\n");
rtMensagens.AppendText("..........." + "\n");
rtMensagens.AppendText(".................");
rtMensagens.AppendText("......................." + "\n");
rtMensagens.AppendText(".................................");
rtMensagens.AppendText("............................................." + "\n");
service.Refresh();
}
string status_final = aew;
if (status_incial == status_final)
{
rtMensagens.Clear();
r.Text = (service.Status.ToString() + " " + aServidores[r.TabIndex] + " " + aServicos[r.TabIndex]);
rtMensagens.AppendText(service.Status.ToString() + " com sucesso" + " " + aServidores[r.TabIndex] + " " + aServicos[r.TabIndex] + "\n" + "\n" + "O serviço " + aServicos[r.TabIndex] + " estava STARTADO, consegui PARAR e STARTEI NOVAMENTE com 100% de sucesso");
r.Enabled = true;
r.Checked = true;
//rtMensagens.BackColor = "red";
button1.Text = aServicos[r.TabIndex] + " Restartado com SUCESSO. Clique aqui para restartar outro serviço";
button1.Enabled = true;
r.Enabled = true;
r.Checked = false;
return;
}
else
MessageBox.Show("Consegui parar o serviço, mas nao consegui starta-lo Novamente");
}
}
}
private void toolStripStatusLabel1_Click(object sender, EventArgs e)
{
}
private void dtgservidores_SelectionChanged(object sender, EventArgs e)
{
int linhadgv = dtgservidores.CurrentRow.Index;
label6.Text = Convert.ToString(linhadgv);
txtservidor.Text = aServidores[linhadgv];
txtservico.Text = aServicos[linhadgv];
}
private void label6_Click(object sender, EventArgs e)
{
}
//altera
private void button4_Click(object sender, EventArgs e)
{
int linhadgv = dtgservidores.CurrentRow.Index;
aServidores[linhadgv] = txtservidor.Text;
aServicos[linhadgv] = txtservico.Text;
//atualiza gridview
dtgservidores.Rows.Clear();
for (int r = 0; r <= aServidores.Length-1; r++)
if (aServidores != null)
{
dtgservidores.Rows.Add(aServidores[r], aServicos[r]);
}
}
private void btnCadastro_Click(object sender, EventArgs e)
{
txtservidor.Clear();
txtservico.Clear();
int linhadgv = dtgservidores.Rows.Count +1;
aServidores[linhadgv] = txtservidor.Text;
aServicos[linhadgv] = txtservico.Text;
dtgservidores.Rows.Clear();
for (int r = 0; r <= aServidores.Length - 1; r++)
if (aServidores != null)
{
dtgservidores.Rows.Add(aServidores[r], aServicos[r]);
}
}
private void button3_Click(object sender, EventArgs e)
{
}
}
}





