Isnin, 14 April 2008

solution; check if user already exist if not register user

YESSS!!!! at last i manage to find the solution for my own validation in asp.net. What i want to do is to check if the user is exist in the database, if yes then the "user already exist" will appear. If not the user will be register in the database. Here is the complete solution of this problems. hope it can help others who experiecne the same problem.

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Using Conn As New MySql.Data.MySqlClient.MySqlConnection("server=localhost; user id=root; password=****; database=****; pooling=false;")

Using Cmd As New MySql.Data.MySqlClient.MySqlCommand
Cmd.Connection = Conn
Cmd.CommandText = "SELECT Count(*) AS thecount FROM staff WHERE staff_id=?staff_id"

With Cmd.Parameters
.Add(New MySql.Data.MySqlClient.MySqlParameter("?staff_id", TextBox1.Text))
End With

Conn.Open()

Dim i As Integer = Cmd.ExecuteScalar()
If i > 0 Then
Label1.Text = "User Already Exist"
End If

If i = 0 Then
Cmd.CommandText = "Insert into staff (staff_id) values (?staff_id)"
Cmd.Parameters.AddWithValue("?staff_id", TextBox1.Text)
Cmd.ExecuteNonQuery()
End If

Conn.Close()

End Using

End Using

End Sub

basically what the code do is execute the statement of cmd.commandtext that is count if the staff id exist in the database. If it return i>0 (means the staff id is exist then it will display the 'user already exist ' message) but if i=0 which means the staff_id is not exist then it will execute the insert statement and the new staff id will be put in the database.

0 ulasan: