在尝试插入之前检查重复值 (ASP.NET)

发布于 2024-11-01 02:07:01 字数 1639 浏览 2 评论 0原文

我有一个表单,其中表单第一页上的两个字段构成主键。我想在尝试插入记录之前检查重复值,因为我不希望用户一路浏览表单才发现他们无法提交它。因此,当用户尝试转到表单的下一页时,我尝试检查重复值。我不太确定该怎么做,果然我收到了一个错误。 (“对象引用未设置为对象的实例。”)问题显然出在我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

初懵 2024-11-08 02:07:01

此错误表明 myValue 变量的内容为空。如果它为空,则不能在其上使用 Length 属性(或任何其他属性)。您必须明确检查 null:

If myValue IsNot Nothing Then

EDIT 1
你的sql查询是错误的。我不知道什么是正确的查询,因为我不知道你的数据库,但我认为你打算写这个:

Dim mySelect As New OleDbCommand("SELECT prefix, course_number FROM tableCourse WHERE prefix=" + checfkPreix + " AND course_number=" + checkNum, myConn)

或类似的东西。您可能需要考虑使用 string.Format 函数形成字符串。而且您还需要确保针对 SQL 注入提供某种保护,因为您形成来自用户输入的查询。在您的情况下,使用 OleDbParameter 可能是合适的。

编辑2

您也正确地提到了 ExecuteScalar 可能存在问题。 ExecuteScalar 应该返回单个值,而您的选择查询返回两个值(前缀和 course_number)。更改它,使其返回单个参数 SELECT prefix FROM 或简单地 SELECT 1 FROM,然后返回查询的其余部分:

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)

Edit 3
您没有在验证器中正确设置失败的验证。
添加

 args.IsValid = False 

到 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:

If myValue IsNot Nothing Then

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:

Dim mySelect As New OleDbCommand("SELECT prefix, course_number FROM tableCourse WHERE prefix=" + checfkPreix + " AND course_number=" + checkNum, myConn)

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 simply SELECT 1 FROM and then the rest of the query:

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)

Edit 3
You are not setting failed validation properly in your validator.
Add

 args.IsValid = False 

inside your if statement.

淡墨 2024-11-08 02:07:01

首先 ExecuteScalar 将仅返回单个值,因此在这种情况下,您只会从结果中获取列 prefix。其次,如果与您的查询不匹配,它将返回 null,因此您的下一次长度检查应考虑到这种情况:

if String.IsNullOrEmpty(myValue) Then
...

参考: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 column prefix from the result. Second if there is no match with your query it will return null, so your next length check should account for that scenario:

if String.IsNullOrEmpty(myValue) Then
...

Reference: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

夜夜流光相皎洁 2024-11-08 02:07:01

如果没有重复,则 myValue 为 null,因此仅当 myValue 不为 null 时才必须应用 .Length(这意味着检查 仅 >null 就足够了;没有 .Length

If Not string.IsNullOrEmpty(myValue) Then

myValue is null if there is no duplicate, so you have to apply .Length only if myValue is not null (which means checking for null only is enough; without .Length)

If Not string.IsNullOrEmpty(myValue) Then
写给空气的情书 2024-11-08 02:07:01

尝试这样的东西(你必须将其适应VB.Net) DBNull 与 Null 或 Nothing 不同,所以你必须将它与两者进行比较

If myValue <> DBNull and not myvalue is nothing Then

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

If myValue <> DBNull and not myvalue is nothing Then
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文