Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么在数据库中插入记录两次而不是一次?_C#_Asp.net_Sql Server 2008 - Fatal编程技术网

C# 为什么在数据库中插入记录两次而不是一次?

C# 为什么在数据库中插入记录两次而不是一次?,c#,asp.net,sql-server-2008,C#,Asp.net,Sql Server 2008,我只在GridView中单击了一次链接按钮,但每次都会插入两次记录。我尝试应用断点,但仍然无法理解。我做错了什么 来源: <asp:GridView ID="GridViewUserScraps" ItemStyle-VerticalAlign="Top" AutoGenerateColumns="False" GridLines="None" Width="100%" ShowHeader="False" runat="server" AlternatingRowStyle-B

我只在GridView中单击了一次链接按钮,但每次都会插入两次记录。我尝试应用断点,但仍然无法理解。我做错了什么

来源:

 <asp:GridView ID="GridViewUserScraps" ItemStyle-VerticalAlign="Top" AutoGenerateColumns="False"
    GridLines="None" Width="100%" ShowHeader="False" runat="server" AlternatingRowStyle-BackColor="#A5A5A5"
    CellPadding="4" ForeColor="#333333" DataKeyNames="ScrapId" 
    OnRowCommand="GridViewRowCommand">
    <Columns>
    <asp:TemplateField>
    <ItemTemplate>
    <table align="left" cellpadding="1" cellspacing="2">
    <tr>
    <td>
    <a href='<%#getUserHREF(Container.DataItem)%>'>
    <img align="middle" src='<%#getSRC(Container.DataItem)%>' border="0" width="50px" /></a>
    </td>
    <td>
    &nbsp;</td>
    </tr>
    </table>
    <div align="justify">
    <%#DataBinder.Eval(Container.DataItem, "Message")%>
    <br />
    <br />
    </div>
    <span class="SmallBlackText">Posted On: &nbsp;</span>
    <asp:Label ID="lblSendDate" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"SendDate")%>'></asp:Label>
    </span>
    <br />
    <%-- <asp:LinkButton ID="lnklike" runat="server" 
    CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" 
    CommandName="LikeCmd">Like</asp:LinkButton>
    &nbsp;&nbsp;&nbsp;
    <asp:LinkButton ID="lnkunlike" runat="server">unlike</asp:LinkButton>--%>

    <asp:LinkButton ID="lnklike" runat="server" CommandName="like" CommandArgument='<%# Eval("ScrapId")%>'>Like</asp:LinkButton>
    <asp:LinkButton ID="lnkunlike" runat="server"  CommandName="unlike" CommandArgument='<%# Eval("ScrapId")%>'>unlike</asp:LinkButton>



    &nbsp;&nbsp;
    <asp:Label ID="lbllike" runat="server" Text="likes:"></asp:Label>
    <%-- <asp:Label ID="lbllikecount" runat="server" Text="0"></asp:Label>--%>


    <asp:Label ID="Label1" runat="server" Text='<%# Controls_GetUserScraps.abc((int)Eval("ScrapId")) %>' />
    <%--<asp:Label ID="Label1" runat="server" Text='<%# WebPageName.StaticMethodName((int)Eval("ScrapId")) %>' />--%>

    &nbsp;&nbsp;
    <asp:Label ID="lblthumbsdown" runat="server" Text="ThumbsDown:"></asp:Label>
    <asp:Label ID="Label2" runat="server" 
    Text='<%# Controls_GetUserScraps.xyz((int)Eval("ScrapId")) %>'></asp:Label>

    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
    <RowStyle BackColor="#EFF3FB" />
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <EditRowStyle BackColor="#2461BF" />
    <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
protected void GridViewRowCommand(Object sender, GridViewCommandEventArgs e)
{
    var scrapId = Int32.Parse(e.CommandArgument.ToString());
    switch (e.CommandName)
    {
    case "like":

        string chklike = "select likestatus from tbl_like where fromid='"+Session["UserId"]+"' and scrapid='"+scrapId+"'";
        int a = dbo.GetLikesMethod(chklike);
        string chkthumbsdown = "select thumbsdownstatus from tbl_like where fromid='"+Session["UserId"]+"' and scrapid='"+scrapId+"'";
        int b = dbo.GetLikesMethod(chkthumbsdown);

        if (a == 0 && b==0)
        {
            string sendlike = "insert into tbl_like (ScrapId,FromId,LikeStatus) values('" + scrapId + "','" + Session["UserId"] + "',1)";
            dbo.insert(sendlike);                       
            GetUserScraps(int.Parse(Request.QueryString["Id"].ToString()));
        }
        else if(a!=0)
        {

            Response.Write("already liked");
        }
        else if (b != 0)
        {
            Response.Write("you can not like something you already downvoted!");
        }

        break;
    case "unlike":

        string chkthumbsdown1 = "select thumbsdownstatus from tbl_like where fromid='"+Session["UserId"]+"' and scrapid='"+scrapId+"'";
        int b1 = dbo.GetLikesMethod(chkthumbsdown1);

        if (b1 == 0)
        {
            string sendthumbsdown = "insert into tbl_like (ScrapId,FromId,thumbsdownstatus) values('" + scrapId + "','" + Session["UserId"] + "',1)";
            dbo.insert(sendthumbsdown);                       
            GetUserScraps(int.Parse(Request.QueryString["Id"].ToString()));
        }
        else
        {
            Response.Write("already THumbsDowned!");
        }

        break;
    }
}

public DataTable insert(string q)
{
    DataTable dt = new DataTable();
    SqlCommand cmd = new SqlCommand(q,con);
    try
    {
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();


    }
    catch { };
    return dt;
}

尝试改用按钮上的OnClick事件处理程序,而不是使用GridViewRowCommand事件。这可能会解决问题。

请尝试使用按钮上的OnClick事件处理程序,而不是使用GridViewRowCommand事件。这可能会解决问题。

了解在数据库中插入行的原因以及使用dataadapter的原因

当您使用da.Fill(dt)时,它已经在执行sql字符串了。 您再次以cmd.ExecuteNonQuery()的形式执行它

尝试这样的代码

  public bool insert(string q)
  {   
     bool result=false;
     SqlCommand cmd = new SqlCommand(q,con);
       try
        {       
          con.Open();
          cmd.ExecuteNonQuery();
          con.Close();
          result=true
        }
       catch { };
       return result; 
      }

用于在数据库中插入行,说明使用dataadapter的原因

当您使用da.Fill(dt)时,它已经在执行sql字符串了。 您再次以cmd.ExecuteNonQuery()的形式执行它

尝试这样的代码

  public bool insert(string q)
  {   
     bool result=false;
     SqlCommand cmd = new SqlCommand(q,con);
       try
        {       
          con.Open();
          cmd.ExecuteNonQuery();
          con.Close();
          result=true
        }
       catch { };
       return result; 
      }

你有一些代码要发布吗?我已经发布了后面的代码。你应该阅读SQL注入攻击的主题,开始使用参数化查询,而不是自己将SQL命令连接在一起@谢谢你!我会记住这一点。:)你有一些代码要发布吗?我已经发布了后面的代码。你应该阅读SQL注入攻击的主题,开始使用参数化查询,而不是自己将SQL命令连接在一起@谢谢你!我会记住这一点。:)成功了,谢谢!你能告诉我什么时候用什么吗?既然你现在已经知道我是一个初学者,可以使用一些技巧。很高兴能帮上忙。当您想要检索记录,即Sql select语句时,您应该使用SqlDataAdapter,而不是ExecuteOnQuery。因此,我想无论何时使用insert、delete或update,我都不需要使用DataAdapter,对吗?它起到了作用,谢谢!你能告诉我什么时候用什么吗?既然你现在已经知道我是一个初学者,可以使用一些技巧。很高兴能帮上忙。当您想要检索记录,即Sql select语句时,您应该使用SqlDataAdapter,而不是ExecuteOnQuery。所以我想无论何时使用insert、delete或update,我都不需要使用DataAdapter,对吗?