我正在制作登录申请。但是当我在我的应用程序中创建一个新用户时,当用户已经存在于数据库中时,我会收到错误。所以我想让我的标签lblOkToe
成为用户已经存在的错误消息。
以下是我正在使用的代码:
private void btnVoegToe_Click(object sender, EventArgs e)
{
// Velden leegmaken
string Wacht = txtWacht.Text;
string Login = txtLogin.Text;
//Parameters Declareren
SqlParameter Para1 = new SqlParameter();
SqlParameter Para2 = new SqlParameter();
Para1.ParameterName = "@Log";
Para2.ParameterName = "@WW";
Para1.Value = Login;
Para2.Value = Wacht;
// SQL Connectie opzetten
SqlConnection Conn = new SqlConnection();
Conn.ConnectionString = @"Integrated Security=true;Initial Catalog=Wachtwoord;Data Source=LAPTOP-PDI9B3LP\SCHOOL";
Conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
// Alles selecteren van tabel Favorieten
cmd.CommandText = "insert into gebruik values (@Log, @WW)";
//Koppelen van SqlParameter met SqlCommand
cmd.Parameters.Add(Para1);
cmd.Parameters.Add(Para2);
int gelukt = cmd.ExecuteNonQuery();
if (gelukt == 1 && )
{
lblOKToe.Text = "De gebruiker" + Login + " is toegevoegd";
cbKeuze.Items.Add(Login);
txtLogin.Text = "";
txtWacht.Text = "";
}
// Database connectie sluiten
Conn.Close();
}
答案 0 :(得分:0)
取决于dB的返回结果:
int gelukt = cmd.ExecuteNonQuery();
如果gelukt为1,则“受影响的记录”为1,并且“记录”已成功插入。
如果gelukt为0则SQL INSERT失败。 很可能是因为你有独特的限制或类似的东西。
所以代码是:
if (gelukt == 1)
{
lblOKToe.Text = "De gebruiker" + Login + " is toegevoegd";
cbKeuze.Items.Add(Login);
txtLogin.Text = "";
txtWacht.Text = "";
}
else //if (gelukt == 0)
{
lblOKToe.Text = "Failed to register, use another name.";
}