我能夠檢查用戶名已經存在使用這樣的代碼:顯示錯誤消息(asp.net)
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Job_Registration_ConnectionString"].ConnectionString);
try
{
conn.Open();
String checkUsr_query = "SELECT count(*) from Job_UserData where username = @Usn";
SqlCommand comm = new SqlCommand(checkUsr_query, conn);
comm.Parameters.AddWithValue("@Usn", TextBox_Usn.Text);
if (!comm.ExecuteScalar().ToString().Equals("0"))
{
Label_Usn.Visible = true;
}
else
{
Label_Usn.Visible = false;
}
}
catch (Exception check_usr)
{
Response.Write(check_usr.ToString());
}
finally
{
if (conn != null)
conn.Close();
}
}
其他變化不請使用單獨的標籤,而不是改變RequiredFieldValidator
中的文字,或者我可以將其與CustomValidator
一起使用並更改其可見性。
我想要做的就是檢查,如果文本框爲空當按鈕被按下這是由RequiredFieldValidator
照顧,一旦我離開的用戶名文本框應該檢查並顯示用戶名是否可用與否和提交提交點擊應該不允許用戶註冊。
目前我使用此代碼:
protected void Button_RegForm_Submit_Click(object sender, EventArgs e)
{
/* if (Label_Usn.Visible)
{
return;
}
* */
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Job_Registration_ConnectionString"].ConnectionString);
try
{
String insert_query = "INSERT into Job_UserData VALUES (@Usn,@Pass,@Village,@Contact,@Address,@Occupation)";
conn.Open();
SqlCommand comm = new SqlCommand(insert_query, conn);
comm.Parameters.AddWithValue("@Usn", TextBox_Usn.Text);
comm.Parameters.AddWithValue("@Pass", TextBox_Pass.Text);
comm.Parameters.AddWithValue("@Village", TextBox_Village.Text);
comm.Parameters.AddWithValue("@Contact", TextBox_Contact.Text);
comm.Parameters.AddWithValue("@Address", TextBox_Address.Text);
comm.Parameters.AddWithValue("@Occupation", TextBox_Occupation.Text);
comm.ExecuteNonQuery();
}
catch (Exception insertError)
{
Response.Write(insertError.ToString());
}
finally
{
if (conn != null)
conn.Close();
}
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Job_Registration_ConnectionString"].ConnectionString);
try
{
conn.Open();
String checkUsr_query = "SELECT count(*) from Job_UserData where username = @Usn";
SqlCommand comm = new SqlCommand(checkUsr_query, conn);
comm.Parameters.AddWithValue("@Usn", TextBox_Usn.Text);
if (!comm.ExecuteScalar().ToString().Equals("0"))
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
catch (Exception check_usr)
{
Response.Write(check_usr.ToString());
}
finally
{
if (conn != null)
conn.Close();
}
}
而且我必須用AutoPostBack
爲用戶名的文本框,以確保重複的用戶名,只要我走出了用戶名文本框的檢查。我發佈的代碼沒有AutoPostBack
,但它允許用戶註冊,即使顯示該用戶名不可用,並且不檢查重複的用戶名,而不點擊提交按鈕。
當我使用AutoPostBack
財產它創造的問題與RequiredFieldValidator
財產,猶如該字段爲空的頁面刷新由於PostBack
後,我離開的用戶名文本框和第二的「需要用戶名」消息閃爍,然後消失我不想要。 我試着將Page_Load
方法中的用戶名檢查部分和RequiredFieldValidator
使用的文本更改屬性,但有時會顯示錯誤的信息。
我該如何做到這一點,或者是否使用Page_load
方法完成,但我做錯了嗎?有沒有更好的方法來做到這一點?
我希望這種形式的工作方式是我相信其他在線形式的工作,如果他們以不同的方式工作,請分享該方法。
作爲一個方面的問題,你真的將查詢發送到服務器的客戶端驗證時,每一次?我會檢查用戶名是否僅在提交時存在。 –
我認爲通常這些表格告訴你,只要你輸入它並更改文本框 –
@abhishekjaiswal,就可以使用用戶名,因爲他需要啓用cookie。,我是對的嗎? – goofyui