1
First this is the bank code I’m using:
CREATE TABLE perguntas (
cod_pergunta SERIAL PRIMARY KEY NOT NULL,
pergunta VARCHAR(500),
opcao_um VARCHAR(500),
opcao_dois VARCHAR(500),
opcao_tres VARCHAR(500),
opcao_quatro VARCHAR(500),
opcao_correta INTEGER,
IDcategoria INTEGER,
CONSTRAINT fk_categoria FOREIGN KEY (IDcategoria) REFERENCES categoria(cod_categoria)
);
CREATE TABLE categoria (
cod_categoria SERIAL PRIMARY KEY NOT NULL,
categoria VARCHAR(15),
descricao VARCHAR(140)
);
I can save the values in the table questions however the combobox value 'category' is recording wrong when I try to save the first value.
Code of the Save button:
private void btnGravar_Click(object sender, EventArgs e)
{
//Verifica qual radio button está selecionado
int valor;
valor = 0;
if (rbCorreta1.Checked == true)
valor = 1;
else if (rbCorreta2.Checked == true)
valor = 2;
else if (rbCorreta3.Checked == true)
valor = 3;
else if (rbCorreta4.Checked == true)
valor = 4;
else
MessageBox.Show("Selecione a resposta correta!");
//Verifica qual o valor do combobox está selecionado e guarda o ID para gravar
string IndexSelecionado = cbCategoria.SelectedIndex.ToString();
string str = "Host=127.0.0.1;Username=postgres;Password=adm;Database=dbquiz";
string gravarsql = "INSERT INTO perguntas (pergunta, opcao_um, opcao_dois, opcao_tres, opcao_quatro, opcao_correta, idcategoria) " + " VALUES ('" + txtPergunta.Text + "', '" + txtResposta1.Text + "', '" + txtResposta2.Text + "', '" + txtResposta3.Text + "', '" + txtResposta4.Text + "', '" + valor + "', '"+ IndexSelecionado + "');";
Npgsql.NpgsqlConnection con = new Npgsql.NpgsqlConnection(str);
Npgsql.NpgsqlCommand cmd = new Npgsql.NpgsqlCommand(gravarsql, con);
cmd.CommandType = CommandType.Text;
con.Open();
try
{
int n = cmd.ExecuteNonQuery();
if (n > 0)
{
MessageBox.Show("Efetuado!");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.ToString());
}
finally
{
con.Close();
}
}
The error that appears is this below, but it only happens when I want to record the first value of the combobox because the other to record only records the wrong index:
Ex.
Categories: 1-Test, 2-Foo, 3-Stack; When I select 2, save 3.
Code to fill the Combobox:
string str = "Host=127.0.0.1;Username=postgres;Password=adm;Database=dbquiz";
Npgsql.NpgsqlConnection con = new Npgsql.NpgsqlConnection(str);
con.Open();
try
{
string sql = "SELECT categoria.cod_categoria, categoria.categoria FROM categoria;";
Npgsql.NpgsqlCommand cmd = new Npgsql.NpgsqlCommand(sql, con);
Npgsql.NpgsqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
this.cbCategoria.DataSource = dt;
this.cbCategoria.DisplayMember = "categoria";
this.cbCategoria.ValueMember = "cod_categoria";
reader.Close();
reader.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
Young man, you can also post the code you use to fill out the combobox?
– Jéf Bueno
All right, I’ll update
– WSS