You are on page 1of 7

Apontamentos C #

Inserção de dados numa tabela – DataTable


Com listbox

private void btnExecutar_Click(object sender, EventArgs e)


{
// Estrutura inicial de uma tabela de nome "lista"
DataTable tabela = new DataTable("lista");

// Adicionar colunas à tabela


tabela.Columns.Add("nome", typeof(string));
tabela.Columns.Add("idade", typeof(int));

// Criar 2 linhas de dados e adicionar à tabela


DataRow novaLinha = tabela.NewRow();
//novaLinha[0] = "Rogério Neves";
//novaLinha[1] = 61;
novaLinha["nome"] = "Rogério Neves";
novaLinha["idade"] = 61;
tabela.Rows.Add(novaLinha);

novaLinha = tabela.NewRow();
//novaLinha[0] = "Paulo Neves";
//novaLinha[1] = 22;
novaLinha["nome"] = "Paulo Neves";
novaLinha["idade"] = 22;
tabela.Rows.Add(novaLinha);

novaLinha = tabela.NewRow();
//novaLinha[0] = "Luís Couto";
//novaLinha[1] = 30;
novaLinha["nome"] = "Luís Couto";
novaLinha["idade"] = 30;
tabela.Rows.Add(novaLinha);

// Apresentar os dados da tabela na lista


lista.Items.Clear(); // limpa a lista
foreach (DataRow linha in tabela.Rows)
{
//lista.Items.Add(linha[0] + " tem " + linha[1]);
lista.Items.Add(linha["nome"] + " tem " + linha["idade"].ToString());
}
}

1
2º Exercício de treino
Com listbox

public partial class frmPrincipal : Form


{
DataTable tabela;

public frmPrincipal()
{
InitializeComponent();
// constroi a tabela
tabela = new DataTable();

// estrutura da tabela
tabela.Columns.Add("nome", typeof(string));
tabela.Columns.Add("idade", typeof(int));
}

private void btnAdicionar_Click(object sender, EventArgs e)


{
// verificar se os campos estão preenchidos
if (txtNome.Text == "" || txtIdade.Text == "")
{
MessageBox.Show("Os dados não estão completos", "Atenção",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtNome.Focus(); // insere o foco na txt
return;
}
// adicionar novLinha
DataRow novaLinha = tabela.NewRow();
// buscar os dados
novaLinha["nome"] = txtNome.Text;
novaLinha["idade"] = Convert.ToInt16(txtIdade.Text);
tabela.Rows.Add(novaLinha);

// fazer o botão apresentar dados funcionar


btnApresentarDados_Click(btnApresentarDados, EventArgs.Empty);

// limpar txt e colocar focus na txtNome


txtNome.Clear();
txtIdade.Clear();
txtNome.Focus();
}

private void btnApresentarDados_Click(object sender, EventArgs e)

2
{
lista.Items.Clear(); // limpa a lista

// verifica a existência de registos na tabela


if (tabela.Rows.Count == 0)
{
lista.Items.Add("Não existem registos na tabela!");
return;
}
// apresentar os dados na tabela
foreach (DataRow linha in tabela.Rows)
{
lista.Items.Add(linha["nome"] + " tem " + linha["idade"]);
}
// apresentar nº de registos
lblResultados.Text = "Registos: " + lista.Items.Count.ToString();
}
}

3
Simplificando o Exercício

public partial class frmPrincipal : Form


{
DataTable tabela;

public frmPrincipal()
{
InitializeComponent();
// constroi a tabela
tabela = new DataTable();

// estrutura da tabela
tabela.Columns.Add("nome", typeof(string));
tabela.Columns.Add("idade", typeof(int));
}

private void btnAdicionar_Click(object sender, EventArgs e)


{
// verificar se os campos estão preenchidos
if (txtNome.Text == "" || txtIdade.Text == "")
{
MessageBox.Show("Os dados não estão completos", "Atenção",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtNome.Focus(); // insere o foco na txt
return;
}

// adicionar novLinha
DataRow novaLinha = tabela.NewRow();
// buscar os dados
novaLinha["nome"] = txtNome.Text;
novaLinha["idade"] = Convert.ToInt16(txtIdade.Text);
tabela.Rows.Add(novaLinha);

lista.Items.Clear(); // limpa a lista

// verifica a existência de registos na tabela


if (tabela.Rows.Count == 0)
{
lista.Items.Add("Não existem registos na tabela!");
return;
}
// apresentar os dados na tabela
foreach (DataRow linha in tabela.Rows)

4
{
lista.Items.Add(linha["nome"] + " tem " + linha["idade"]);
}
// apresentar nº de registos
lblResultados.Text = "Registos: " + lista.Items.Count.ToString();

// limpar txt e colocar focus na txtNome


txtNome.Clear();
txtIdade.Clear();
txtNome.Focus();
}
}

5
Com dataGridView
A propriedade AllowUserToAddRows da dataGrid coloca-se false

public partial class frmPrincipal : Form


{
DataTable tabela;

public frmPrincipal()
{
InitializeComponent();
// constroi a tabela
tabela = new DataTable();

// estrutura da tabela
tabela.Columns.Add("nome", typeof(string));
tabela.Columns.Add("idade", typeof(int));
}

private void btnAdicionar_Click(object sender, EventArgs e)


{
// verificar se os campos estão preenchidos
if (txtNome.Text == "" || txtIdade.Text == "")
{
MessageBox.Show("Os dados não estão completos", "Atenção",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtNome.Focus(); // insere o foco na txt
return;
}
// adicionar novLinha
DataRow novaLinha = tabela.NewRow();
// buscar os dados
novaLinha["nome"] = txtNome.Text;
novaLinha["idade"] = Convert.ToInt16(txtIdade.Text);
tabela.Rows.Add(novaLinha);

// Inserir os dados na dataGrid


dataGrid.DataSource = tabela;
lblResultados.Text = "Registos: " + dataGrid.Rows.Count.ToString();

// limpar txt e colocar focus na txtNome


txtNome.Clear();
txtIdade.Clear();
txtNome.Focus();
}
}

6
Criar e Comunicar com base de dados
Três passos fundamentais:

1. Ligação à base de dados;


2. Execução da query ou queries;
3. Fechar a ligação à base de dados;

You might also like