使用asp:control插入时避免重复数据

时间:2011-07-03 03:07:37

标签: asp.net

我有一个ASP.NET代码,我用它来插入和查看* .mdb文件中的数据 当我重新加载浏览器重新加载时,它会插入相同的旧数据。         

    <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" 
        DataKeyNames="user_id" DataSourceID="AccessDataSource1" Height="50px" 
        Width="125px" DefaultMode="Insert">
        <Fields>
            <asp:BoundField DataField="user_id" HeaderText="user_id" InsertVisible="False" 
                ReadOnly="True" SortExpression="user_id" />
            <asp:BoundField DataField="user_name" HeaderText="user_name" 
                SortExpression="user_name" />
            <asp:BoundField DataField="user_pass" HeaderText="user_pass" 
                SortExpression="user_pass" />
            <asp:BoundField DataField="user_email" HeaderText="user_email" 
                SortExpression="user_email" />
            <asp:CommandField ButtonType="Button" ShowInsertButton="True" />
        </Fields>
    </asp:DetailsView>

    <div ID="Div1" runat="server"></div>


    <asp:AccessDataSource ID="AccessDataSource1" runat="server" 
        DataFile="~/App_Data/esn.mdb" 
        SelectCommand="SELECT * FROM [user]"
        InsertCommand="INSERT INTO [user] ([user_name], [user_pass], [user_email]) VALUES (@user_name, @user_pass, @user_email)">
        <InsertParameters>
            <asp:Parameter Name="user_name" Type="String" />
            <asp:Parameter Name="user_pass" Type="String" />
            <asp:Parameter Name="user_email" Type="String" />
        </InsertParameters>
    </asp:AccessDataSource>





    <asp:GridView ID="GridView1" runat="server" 
        AutoGenerateColumns="False" DataKeyNames="user_id" 
        DataSourceID="AccessDataSource1">
        <Columns>
            <asp:BoundField DataField="user_id" HeaderText="user_id" InsertVisible="False" 
                ReadOnly="True" SortExpression="user_id" />
            <asp:BoundField DataField="user_name" HeaderText="user_name" 
                SortExpression="user_name" />
            <asp:BoundField DataField="user_pass" HeaderText="user_pass" 
                SortExpression="user_pass" />
            <asp:BoundField DataField="user_email" HeaderText="user_email" 
                SortExpression="user_email" />
        </Columns>
    </asp:GridView>

</form>

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

使用viewstate或session存储标记&#34; hasSaved&#34;。当页面第一次加载时:

    protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        ViewState["hasSaved"] = false;
}

并更改&#34; hasSaved&#34;的值保存数据时为true,请注意如果&#34; hasSaved&#34;则保存该值。是假的 请在此处查看完整代码 Avoid Repeated insertion due to page refresh