I have a small problem that takes me for a day and until now it is not resolve, I am trying to save a record that is not existed in the database, if the user input was already existed, it will not save but the thing is it works somehow but then I notice when i tried to validate the 2nd row and input the same values like username or email boom! the data was inserted so it cause duplicates. How to fix this? can you help me please? thanks
here’s my code.
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblInternetAccount.Value = lblAccountNo.Text.ToString() + txtUsername.Text.ToString();
DataSet ds = new DataSet();
ds = (startWebService.getAllUsers());
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow drow in ds.Tables[0].Rows)
{
string username = drow["UserName"].ToString();
string acctNo = drow["AccountNumber"].ToString();
if (username != txtUsername.Text.ToString() || acctNo != lblAccountNo.Text.ToString())
{
startWebService.insertUser(lblAccountNo.Text.ToString(), txtUsername.Text.ToString(), txtPassword.Text.ToString(), txtUsername.Text.ToString(), cboQuestion.Text.ToString(), txtAnswer.Text.ToString(), lblInternetAccount.Value.ToString(), txtPassword.Text.ToString());
lblMessage.Text = "Record Updated!";
}
else
{
lblMessage.Text = "<br>Unable to create record because account number/email is already registered.Please login instead.<br><br>";
}
}
}
}
web services:
private DataSet GetDataSet(string strSPROC)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strSPROC;
conn.Open();
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = cmd;
DataSet dsMT = new DataSet();
myDataAdapter.Fill(dsMT);
return dsMT;
conn.Close();
}
[WebMethod]
public void insertUser(string accountNo, string userName, string pAssword, string eMail, string secretQuestion, string secretAnswer,string onlineActNo,string acctkey)
{
Insert("ELMS_CREATEMEMBER", accountNo, userName, pAssword, eMail, secretQuestion, secretAnswer, onlineActNo,acctkey);
}
You were almost there. You just perform the actual insert to early (which will lead to many inserts).
What you’re doing is this:
What you need to do is first check all existing records and only then, when no record matched your new record, insert the new record.
A modified code example: