在尝试插入之前检查重复值 (ASP.NET)
我有一个表单,其中表单第一页上的两个字段构成主键。我想在尝试插入记录之前检查重复值,因为我不希望用户一路浏览表单才发现他们无法提交它。因此,当用户尝试转到表单的下一页时,我尝试检查重复值。我不太确定该怎么做,果然我收到了一个错误。 (“对象引用未设置为对象的实例。”)问题显然出在我的 if 语句中,“如果 myValue.Length > 0 那么”,但我不确定需要用什么来代替它。
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
'get values
Dim checkPrefix = txtCoursePrefix.Text
Dim checkNum = txtCourseNum.Text
'db connectivity
Dim myConn As New OleDbConnection
myConn.ConnectionString = AccessDataSource1.ConnectionString
myConn.Open()
'select records
Dim mySelect As New OleDbCommand("SELECT prefix, course_number FROM tableCourse WHERE prefix='checkPrefix' AND course_number='checkNum'", myConn)
'execute(Command)
Dim myValue As String = mySelect.ExecuteScalar()
'check if record exists
If myValue.Length > 0 Then
CustomValidator1.ErrorMessage = "some exp text"
CustomValidator1.SetFocusOnError = "true"
CustomValidator1.IsValid = "false"
End If
End Sub
我想我会发布最终的解决方案:
'select records
Dim mySelect As New OleDbCommand("SELECT 1 FROM tableCourse WHERE prefix=? AND course_number=?", myConn)
mySelect.Parameters.AddWithValue("@checkPrefix", checkPrefix)
mySelect.Parameters.AddWithValue("@checkNum", checkNum)
'execute(Command)
Dim myValue = mySelect.ExecuteScalar()
'check if record exists
If myValue IsNot Nothing Then
CustomValidator1.SetFocusOnError = True
args.IsValid = False
End If
I have a form where two fields on the first page of the form make up the primary key. I want to check for duplicate values before attempting to insert the record, since I don't want the user to go all the way through the form only to find out they can't submit it. So I'm trying to check for duplicate values when the user tries to go to the next page of the form. I wasn't quite sure how to do it, and sure enough I'm getting an error. ("Object reference not set to an instance of an object.") The problem is apparently in my if statement, "If myValue.Length > 0 Then", but I'm not sure what needs to be in place of that.
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
'get values
Dim checkPrefix = txtCoursePrefix.Text
Dim checkNum = txtCourseNum.Text
'db connectivity
Dim myConn As New OleDbConnection
myConn.ConnectionString = AccessDataSource1.ConnectionString
myConn.Open()
'select records
Dim mySelect As New OleDbCommand("SELECT prefix, course_number FROM tableCourse WHERE prefix='checkPrefix' AND course_number='checkNum'", myConn)
'execute(Command)
Dim myValue As String = mySelect.ExecuteScalar()
'check if record exists
If myValue.Length > 0 Then
CustomValidator1.ErrorMessage = "some exp text"
CustomValidator1.SetFocusOnError = "true"
CustomValidator1.IsValid = "false"
End If
End Sub
Thought I'd post the final solution:
'select records
Dim mySelect As New OleDbCommand("SELECT 1 FROM tableCourse WHERE prefix=? AND course_number=?", myConn)
mySelect.Parameters.AddWithValue("@checkPrefix", checkPrefix)
mySelect.Parameters.AddWithValue("@checkNum", checkNum)
'execute(Command)
Dim myValue = mySelect.ExecuteScalar()
'check if record exists
If myValue IsNot Nothing Then
CustomValidator1.SetFocusOnError = True
args.IsValid = False
End If
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
此错误表明 myValue 变量的内容为空。如果它为空,则不能在其上使用 Length 属性(或任何其他属性)。您必须明确检查 null:
EDIT 1
你的sql查询是错误的。我不知道什么是正确的查询,因为我不知道你的数据库,但我认为你打算写这个:
或类似的东西。您可能需要考虑使用 string.Format 函数形成字符串。而且您还需要确保针对 SQL 注入提供某种保护,因为您形成来自用户输入的查询。在您的情况下,使用 OleDbParameter 可能是合适的。
编辑2
您也正确地提到了 ExecuteScalar 可能存在问题。 ExecuteScalar 应该返回单个值,而您的选择查询返回两个值(前缀和 course_number)。更改它,使其返回单个参数
SELECT prefix FROM
或简单地SELECT 1 FROM
,然后返回查询的其余部分:Edit 3
您没有在验证器中正确设置失败的验证。
添加
到 if 语句中。
This error indicates that the content of myValue variable is null. If it's null you can't use Length property (or any other property for that matter) on it. You have to check for null explicitly:
EDIT 1
Your sql query is wrong. I don't know what would be the right query, as I don't know your database, but I think you intender to write this:
or something to that effect. You might want to consider using string.Format function for forming the string. And you also need to make sure that there is some kind of protection against SQL Injection, since you form your query from user input. In your case using of OleDbParameter might be appropriate.
Edit 2
You also right to mention that there might be a problem with ExecuteScalar. ExecuteScalar is supposed to return a single value and your select query are returning two (prefix and course_number). Change it so that it returns a single parameter
SELECT prefix FROM
or simplySELECT 1 FROM
and then the rest of the query:Edit 3
You are not setting failed validation properly in your validator.
Add
inside your if statement.
首先
ExecuteScalar
将仅返回单个值,因此在这种情况下,您只会从结果中获取列prefix
。其次,如果与您的查询不匹配,它将返回null
,因此您的下一次长度检查应考虑到这种情况:参考:http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
First
ExecuteScalar
will only return a single value, so in this case you are only going to get the columnprefix
from the result. Second if there is no match with your query it will returnnull
, so your next length check should account for that scenario:Reference: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
如果没有重复,则
myValue
为 null,因此仅当myValue
不为 null 时才必须应用.Length
(这意味着检查仅 >null
就足够了;没有.Length
)myValue
is null if there is no duplicate, so you have to apply.Length
only ifmyValue
is not null (which means checking fornull
only is enough; without.Length
)尝试这样的东西(你必须将其适应VB.Net) DBNull 与 Null 或 Nothing 不同,所以你必须将它与两者进行比较
try something like this instead (you will have to adapt it to VB.Net) DBNull is different from Null or Nothing so you have to compare it to both