ASP.net check value exists

Capodecina
Permabanned
Joined
31 Dec 2003
Posts
5,172
Location
Barrow-In-Furness
I'm inserting one value into a table and everything works fine, the only problem is when the value has already been entered.

I'm using a DetailsView with just one input field, how can I check if the value exists already so that the application doesn't crash and an Label or error is just displayed instead?

I'm trying to do it using the following method but it's not working..i'm getting the following error on the line i've highlighted:

"Reference to non shared member requires an object reference"

Code:
Partial Class ManHours_Categories
    Inherits System.Web.UI.Page

    Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting

        Dim isDuplicate As Boolean = ManHoursTableAdapters.tblCategoriesTableAdapter.GetCategories(e.Values("Name")) IsNot Nothing

        If isDuplicate Then

            Label1.Text = String.Format("Category '(0)' already exists", e.Values("Name"))
            e.Cancel = True
        End If
    End Sub

End Class

Code:
<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Copy of Categories.aspx.vb" Inherits="ManHours_Categories" title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    Currently active categories:<br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="Name" DataSourceID="ObjectDataSource1" GridLines="None" Width="141px">
        <Columns>
            <asp:BoundField DataField="Name" ReadOnly="True" ShowHeader="False" SortExpression="Name">
                <HeaderStyle HorizontalAlign="Left" />
            </asp:BoundField>
            <asp:CommandField ShowDeleteButton="True" />
        </Columns>
    </asp:GridView>
    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="Delete" OldValuesParameterFormatString="original_{0}" SelectMethod="GetCategories"
        TypeName="ManHoursTableAdapters.tblCategoriesTableAdapter" UpdateMethod="Update">
        <DeleteParameters>
            <asp:Parameter Name="Original_Name" Type="String" />
        </DeleteParameters>
        <UpdateParameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="Original_Name" Type="String" />
        </UpdateParameters>
    </asp:ObjectDataSource>
    <br />
    <br />
    <br />
    To create a new time code below, enter the name and click Insert.<br />
     
    <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="Name"
        DataSourceID="ObjectDataSource2" DefaultMode="Insert" GridLines="None" Height="86px"
        Width="296px">
        <Fields>
            <asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name">
                <ItemStyle VerticalAlign="Top" />
                <HeaderStyle VerticalAlign="Top" />
            </asp:BoundField>
            <asp:CommandField ShowInsertButton="True" />
        </Fields>
    </asp:DetailsView>
    <asp:ObjectDataSource ID="ObjectDataSource2" runat="server" DeleteMethod="Delete"
        InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetCategories"
        TypeName="ManHoursTableAdapters.tblCategoriesTableAdapter" UpdateMethod="Update">
        <DeleteParameters>
            <asp:Parameter Name="Original_Name" Type="String" />
        </DeleteParameters>
        <UpdateParameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="Original_Name" Type="String" />
        </UpdateParameters>
        <InsertParameters>
            <asp:Parameter Name="Name" Type="String" />
        </InsertParameters>
    </asp:ObjectDataSource>
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
     <br />
</asp:Content>
 
You need to create a new adapter variable for your tableadapter and use that to reference GetCategories.

You've already done it in your previous posts before now ;)

Code:
        Dim codestatusAdapter As New ManHoursTableAdapters.CodeStatusTableAdapter()
        Dim codeStatus As ManHours.CodeStatusDataTable

        codeStatus = codestatusAdapter.GetCodeStatus()

Above taken from http://forums.overclockers.co.uk/showpost.php?p=10578797&postcount=15
 
Doh!

I still get the same error when using:

Code:
Imports ManHoursTableAdapters


Partial Class ManHours_Categories
    Inherits System.Web.UI.Page

    Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting


        Dim categoriesAdapter As New ManHoursTableAdapters.tblCategoriesTableAdapter
        Dim categories As New ManHours.tblCategoriesDataTable

        categories = categoriesAdapter.GetCategories()

        Dim isDuplicate As Boolean = [B][U][COLOR="Red"]ManHoursTableAdapters.tblCategoriesTableAdapter.GetCategories[/COLOR][/U][/B](e.Values("Name")) IsNot Nothing

        If isDuplicate Then

            Label1.Text = String.Format("Category '(0)' already exists", e.Values("Name"))
            e.Cancel = True

        End If
    End Sub

End Class
 
The following is causing the error, delete it as you don't need it anymore:
Code:
ManHoursTableAdapters.tblCategoriesTableAdapter.GetCategories(e.Values("Name"))

Everything associated with GetCategories() is now in the categories variable you created:
Code:
Dim categoriesAdapter As New ManHoursTableAdapters.tblCategoriesTableAdapter
Dim categories As New ManHours.tblCategoriesDataTable

categories = categoriesAdapter.GetCategories()

I would also add e.Values("Name") to the above line.

If you want to know if that record already exists, then use categories.Count to find out how many records it has found and use this in your if statement instead.

Code:
If categories.Count = 1 then
      ' If there is a record found, add your code here to do whatever you want
End If

If there is going to be more than one record related to e.Values("Name") then use > 0 instead of = 1.
 
Thanks, but it doesn't like me adding the e.Value line to there..

The line highlighted gives me the error

Value of type 'ManHours.tblCategoriesRow' cannon be converted to 'ManHours.tblCategories.DataTable'.

Code:
Imports ManHoursTableAdapters


Partial Class ManHours_Categories
    Inherits System.Web.UI.Page

    Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting


        Dim categoriesAdapter As New ManHoursTableAdapters.tblCategoriesTableAdapter
        Dim categories As New ManHours.tblCategoriesDataTable

        [B]categories = categoriesAdapter.GetCategories(e.Values("Name"))[/B]

        If categories.Count > 0 Then
            Label1.Text = "Record already exists, please try again"
        End If
    End Sub

End Class
 
Change this line:

Code:
Dim categories As New ManHours.tblCategoriesDataTable

To:

Code:
Dim categories As ManHours.tblCategoriesDataTable
 
Still getting the same error:

Error 1 Value of type 'ManHours.tblCategoriesRow' cannot be converted to 'ManHours.tblCategoriesDataTable'. H:\Visual Studio 2005\WebSites\ManHoursUPDATED\Management\Copy of Categories.aspx.vb 13 22 H:\...\ManHoursUPDATED\

Code:
Imports ManHoursTableAdapters


Partial Class ManHours_Categories
    Inherits System.Web.UI.Page

    Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting


        Dim categoriesAdapter As New ManHoursTableAdapters.tblCategoriesTableAdapter
        Dim categories As ManHours.tblCategoriesDataTable

        categories = [COLOR="Red"][B]categoriesAdapter.GetCategories(e.Values("Name"))[/B][/COLOR]

        If categories.Count > 0 Then
            Label1.Text = "Record already exists, please try again"
        End If
    End Sub

End Class

:(
 
Hmm, OK try it a different way.

Code:
Partial Class ManHours_Categories
    Inherits System.Web.UI.Page

    Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting

        Dim categoriesAdapter As New ManHoursTableAdapters.tblCategoriesTableAdapter()
        ' Also note the brackets on the end of the above line
        Dim categories As ManHours.tblCategoriesDataTable = categoriesAdapter.GetCategories(e.Values("Name"))

        If categories.Count > 0 Then
            Label1.Text = "Record already exists, please try again"
        End If
    End Sub

End Class

If this doesn't work it's something to do with your GetCategories query.
 
That's still leaving me with the same error :(

The GetCategories query looks fine to me?

SELECT Name FROM lward.tblCategories ORDER BY Name
 
Ah that's why then.

Take out e.Values("Name").

When you put it in your first post I thought it was a query with a parameter.
 
That allows me to run it, but when I enter a value that already exists it doesn't set the label and instead crashes and gives the following error:

Violation of PRIMARY KEY constraint 'PK_tblCategories_1'. Cannot insert duplicate key in object 'tblCategories'.
The statement has been terminated.


Eeeek :(

Thanks for this by the way, you're a good guy :D
 
Yes, it will continue running through your code, you need to exit out of the DetailsView_ItemInserting Sub to stop it inserting.

In the if statement after setting the text for the label add:

e.Cancel = true
 
I tried that but it doesn't stop it :\

Code:
Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting

        Dim categoriesAdapter As New ManHoursTableAdapters.tblCategoriesTableAdapter()

        Dim categories As ManHours.tblCategoriesDataTable = categoriesAdapter.GetCategories

        If categories.Count = 1 Then
            Label1.Text = "Record already exists, please try again"
            e.Cancel = True
        End If
    End Sub
 
Look at the error message.

it's pulling data back as an "ManHours.tblCategoriesRow" inherited from datarow object and it's trying to be cast into a ManHours.tblCategoriesDataTable type which inherits from datatable.

I would look at the line
Dim categories As ManHours.tblCategoriesDataTable = categoriesAdapter.GetCategories(e.Values("Name"))

It probably returns an array of tblCategoriesRow.
 
This is the msdn link for the DetailsViewInsertEventArgs http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsviewinserteventargs.aspx

Comment out all your code in the method. have just
e.Cancel = true​

Code:
Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting

            e.Cancel = True

End Sub

Then try inserting something, if this isn't being inserted into the table then you know that you can stop an insert. Then you just need to find out if the value exists in the datatable. Initially try using a foreach loop categories something like this.

Code:
For Each dr as datarow in categories.datarows
[INDENT]
if e.Values("Name") = dr("Name") then
[INDENT]e.cancel = true
exit for[/INDENT]
end if[/INDENT]
next
 
Back
Top Bottom