如何在GridView中添加Like / Different功能?

时间:2013-02-14 07:24:01

标签: c# asp.net sql-server-2008

如果我在数据库中手动输入值,那么我可以在墙上查看它,但我不知道如何在点击“喜欢”时以编程方式插入值。 我希望点击“喜欢”(在msg下面的每一行中)触发的查询是"insert into tbl_like (ScrapId,FromId,LikeStatus) values(A*,sessionUserID,1)";

A * =这必须是点击之类的特定行的Scrapid。

数据库表: Scrap_Table: ScrapId | FromId | ToId |消息

Like_table:

LikeId | ScrapId | FromId | LikeStatus

源代码:

   <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" 
                OnItemCommand="CommandLinkClicked">
                <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")) %>' />--%>

                        </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>

代码背后:

DataBaseClass dbClass = new DataBaseClass();
public DataTable dt;

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {

        GetUserScraps(int.Parse(Request.QueryString["Id"].ToString()));
    }
}
public void GetUserScraps(int Id)
{

    string getUserScraps = "SELECT u.Id as UserId,u.firstname,u.ImageName,s.FromId,s.ToId,s.Message,s.SendDate,s.ID as ScrapId FROM [User] as u, Scrap as s WHERE u.Id=s.FromId AND s.ToId='" + Request.QueryString["Id"].ToString() + "'";
  //string getlikes = "select COUNT(*) from tbl_like inner join Scrap on tbl_like.scrapid=Scrap.Id where tbl_like.likestatus=1 and tbl_like.scrapid='"+<%#DataBinder.Eval(Container.DataItem,"ScrapId")%>+"'";
  //  <%#DataBinder.Eval(Container.DataItem,"ScrapId")%>


    dt = dbClass.ConnectDataBaseReturnDT(getUserScraps);
    if (dt.Rows.Count > 0)
    {
        GridViewUserScraps.DataSource = dt;
        GridViewUserScraps.DataBind();
    }
}

public string getUserHREF(object sURL)
{
    DataRowView dRView = (DataRowView)sURL;
    string Id = dRView["UserId"].ToString();
    return ResolveUrl("~/UserDetails.aspx?Id=" + Id);
}

public string getSRC(object imgSRC)
{
    DataRowView dRView = (DataRowView)imgSRC;
    string ImageName = dRView["ImageName"].ToString();
    if (ImageName == "NoImage")
    {
        return ResolveUrl(@"~/Site_Images/image_missing.jpg");
    }
    else
    {
        return ResolveUrl("~/UserImage/" + dRView["ImageName"].ToString());
    }
}

public static int abc(int scrpid)
{

    string getlikes = "select COUNT(*) from tbl_like inner join Scrap on tbl_like.scrapid=Scrap.Id where tbl_like.likestatus=1 and tbl_like.scrapid='"+scrpid+"'";

    dboperation dbo = new dboperation();
    int a = dbo.GetLikesMethod(getlikes);

    return a;
}


protected void CommandLinkClicked(object sender, DataGridCommandEventArgs e)
{
    var scrapId = Int32.Parse(e.CommandArgument.ToString());
    switch (e.CommandName)
    {
        case "like":
            var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString); //your connection string
            var cmd = new SqlCommand("insert into tbl_like (ScrapId,FromId,LikeStatus) values(@scrapId,@sessionUser,1)");
            cmd.Parameters.AddWithValue("@scrapId", scrapId);
            cmd.Parameters.AddWithValue("@sessionUser", Session["UserId"]);
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            break;
        case "unlike":
            //do stuff
            break;
    }
}

}

1 个答案:

答案 0 :(得分:1)

您必须将OnItemCommand事件添加到网格中才能处理链接按钮上的点击。此外,两个链接按钮都必须设置CommandNameCommandArgument

按如下方式更改您的HTML:

<asp:GridView .... OnRowCommand="GridViewRowCommand">

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

</asp:GridView>

这是代码背后的事件:

protected void GridViewRowCommand(Object sender, GridViewCommandEventArgs e)
{
    var scrapId = Int32.Parse(e.CommandArgument.ToString());
    switch (e.CommandName)
    {
        case "like" : 
                using (var con = new SqlConnection("connection_string")) //your connection string
                {
                   var cmd = new SqlCommand("insert into tbl_like (ScrapId,FromId,LikeStatus) values(@scrapId,@sessionUser,1)");
                   cmd.Parameters.AddWithValue("@scrapId", scrapId);
                   cmd.Parameters.AddWithValue("@sessionUser", Session[User]); 
                   cmd.Connection = con;
                   con.Open();
                   cmd.ExecuteNonQuery();
                }
                break;
        case "unlike" : 
                //do stuff
                break;
    }
}