开发者

Formview: check if record exist when user try to insert data ASP.NET C#

Is there a way were I could generate a message box if a record exist in the database after the user clicked the insert link button? I want the formview to check if record exist if not make an insert.

Help would be much appreciated. Thanks in advance :)

Here's a sample of my code:

Manage Books

Add/Remove Books

Note: For the book ID/ISBN please refer to the barcode in the ISBN, usually located at the back of the book. A barcode reader is required.

    <EditItemTemplate>

        Book ID/ISBN:
        <asp:Label ID="bookidLabel1" runat="server" Text='<%# Eval("bookid") %>' />
        <br />

        Title:
        <asp:TextBox ID="booktitleTextBox" runat="server" 
            Text='<%# Bind("booktitle") %>' />
        <br />

        Author's lastname:
        <asp:TextBox ID="lastnameTextBox" runat="server" 
            Text='<%# Bind("lastname") %>' />
        <br />

        Author's firstname:
        <asp:TextBox ID="firstnameTextBox" runat="server" 
            Text='<%# Bind("firstname") %>' />
        <br />

        Description:
        <asp:TextBox ID="descriptionTextBox" runat="server" 
            Text='<%# Bind("description") %>' />
        <br />

        Category:
        <asp:TextBox ID="categoryidTextBox" runat="server" 
            Text='<%# Bind("categoryid") %>' />
        <br />

        Date added:
        <asp:TextBox ID="dateaddedTextBox" runat="server" 
            Text='<%# Bind("dateadded") %>' />
        <br />

        Status:
        <asp:TextBox ID="statusidTextBox" runat="server" 
            Text='<%# Bind("statusid") %>' />
        <br />

        Quantity:
        <asp:TextBox ID="quantityTextBox" runat="server" 
            Text='<%# Bind("quantity") %>' />
        <br />

        name:
        <asp:TextBox ID="nameTextBox" runat="server" Text='<%# Bind("name") %>' />
        <br />
        <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" 
            CommandName="Update" Text="Update" />
        &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" 
            CausesValidation="False" CommandName="Cancel" Text="Cancel" />

    </EditItemTemplate>

    <InsertItemTemplate>

        Book ID:
        <asp:TextBox ID="bookidTextBox" runat="server" Text='<%# Bind("bookid") %>' />
        <asp:RequiredFieldValidator ID="RequesFieldValidator1" runat="server" ErrorMessage="* Required" ControlToValidate="bookidTextBox" ValidationGroup="InsertBook">
        </asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator" runat="server" Display="Dynamic" ControlToValidate="bookidTextBox" ValidationExpression="^([\S\s]{13,13})$" ErrorMessage="Invalid ID/ISBN. Please try again" ValidationGroup="InsertBook">
        </asp:RegularExpressionValidator>
        <br />

        Title:
        <asp:TextBox ID="booktitleTextBox" runat="server" 
            Text='<%# Bind("booktitle") %>' />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="* Required" ControlToValidate="booktitleTextBox" ValidationGroup="InsertBook">
        </asp:RequiredFieldValidator>
        <br />

        Author's lastname:
        <asp:TextBox ID="lastnameTextBox" runat="server" 
            Text='<%# Bind("lastname") %>' />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="* Required" ControlToValidate="lastnameTextBox" ValidationGroup="InsertBook">
        </asp:RequiredFieldValidator>
        <br />

        Author's firstname:
        <asp:TextBox ID="firstnameTextBox" runat="server" 
            Text='<%# Bind("firstname") %>' />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="* Required" ControlToValidate="firstnameTextBox" ValidationGroup="InsertBook">
        </asp:RequiredFieldValidator>
        <br />

        Description:
        <asp:TextBox ID="descriptionTextBox" runat="server" 
            Text='<%# Bind("description") %>' />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="* Required" ControlToValidate="descriptionTextBox" ValidationGroup="InsertBook">
        </asp:RequiredFieldValidator>
        <br />

        Category:
        <asp:DropDownList ID="DropDownList1" runat="server" 
            DataSourceID="categoryDataSource" DataTextField="name" 
            DataValueField="categoryid" SelectedValue='<%# Bind("categoryid", "{0}") %>'>
        </asp:DropDownList>

        <asp:SqlDataSource ID="categoryDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>" 
            SelectCommand="SELECT [categoryid], [name] FROM [TblCategory]">
        </asp:SqlDataSource>
        <br />

        Date added:
        <asp:TextBox ID="dateaddedTextBox" runat="server" 
            Text='<%# Bind("dateadded") %>'/>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="* Required" ControlToValidate="dateaddedTextBox" ValidationGroup="InsertBook">
        </asp:RequiredFieldValidator>
        <%--<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
        ControlToValidate="dateaddedTextBox" ErrorMessage="RegularExpressionValidator"
        ValidationExpression="(19|20)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])">
        </asp:RegularExpressionValidator>--%>
        <br />

        Status:
        &l开发者_如何学运维t;asp:DropDownList ID="DropDownList2" runat="server" 
            DataSourceID="statusDataSource" DataTextField="statusname" 
            DataValueField="statusid" SelectedValue='<%# Bind("statusid", "{0}") %>'>
        </asp:DropDownList>

        <asp:SqlDataSource ID="statusDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>" 
            SelectCommand="SELECT [statusid], [statusname] FROM [BookStatus]">
        </asp:SqlDataSource>
        <br />

        Quantity:
        <asp:TextBox ID="quantityTextBox" runat="server" 
            Text='<%# Bind("quantity") %>' />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ErrorMessage="* Required" ControlToValidate="quantityTextBox" ValidationGroup="InsertBook">
        </asp:RequiredFieldValidator>
        <br />

        <asp:Button ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Add" ValidationGroup="InsertBook"/>

        <asp:Button ID="InsertCancelButton" runat="server" 
            CausesValidation="False" CommandName="Cancel" Text="Cancel" />

    </InsertItemTemplate>

    <ItemTemplate>
        <asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" 
            CommandName="New" Text="New" />
    </ItemTemplate>
    <EmptyDataTemplate>
        <asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" 
            CommandName="New" Text="New" />
    </EmptyDataTemplate>
    <HeaderTemplate>
        Add a new book
    </HeaderTemplate>

</asp:FormView>


You can check in the ItemInserting method.

Something like:

void FormViewName_ItemInserting(object sender, FormViewInsertEventArgs e)
{
  string somevalue = e.Values["somefieldtoget"];
  //make your calls to the DB to check the somevalue doesn't exist 

  if(exists)
    e.Cancel = true; 
}

You can also do this on the data sources Inserting Method (sql datasource assumed) as well....

void datasourcename_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
...
}

Another approach as mentioned by @steve-wellens is if you have a primary key that is based on one or more of the fields in the form view (not an auto generated number then below will work great for catching an attempt to insert a duplicate key/record.

void FormViewName_ItemInserted(object sender, FormViewInsertedEventArgs e)
{
  if (e.Exception != null)
  {
   if (((SqlException)e.Exception).Number == 2627)
   {
    e.ExceptionHandled = true;
    e.KeepInInsertMode = true;
    // Display error message.
   }
  }
}


It would be better to put a unique index on the table and catch exceptions that occur when an attempt is made to insert a duplicate record.

It's the simplest way to ensure integrity. Otherwise you have to start a read transaction to handle the case where between the time you check and the time you insert, some other process is doing the exact same thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜