在GridView中获取当前id,并在按钮单击时将其作为id插入另一个表中

时间:2015-05-11 11:43:36

标签: sql asp.net gridview sqlcommand

我有一个名为Documents和GridView的表,我在其中显示了一些信息。在ItemTemplate中,我将按钮作为评级系统。我想要做的是从Documents表中获取DocumentID并在名为RatingTable的表中将其用作ID,其中DocumentID作为主键和外键,并且评级为tinyint。

以下是gridview的代码:

<asp:GridView ID="SearchView" runat="server" AutoGenerateColumns="false" OnSelectedIndexChanged="SearchView_SelectedIndexChanged" ShowHeaderWhenEmpty="true" EmptyDataText="Ingen oppføringer">
        <Columns>
            <asp:BoundField DataField="FileName" HeaderText="Filnavn" />
            <asp:BoundField DataField="ReportCount" HeaderText="Antall rapporteringer" />
            <asp:BoundField DataField="Tags" HeaderText="Tags" />
            <asp:BoundField DataField="CourseCode" HeaderText="Fagkode" />
            <asp:TemplateField HeaderText="Rating">
                <ItemTemplate>
                    <asp:ImageButton class="myButtonLink" ImageUrl="~/Images/empty_star.png" ID="rate1" runat="server" OnClick="rate1_Click"/>
                    <asp:ImageButton class="myButtonLink" ImageUrl="~/Images/empty_star.png" ID="rate2" runat="server" OnClick="rate2_Click"/>
                    <asp:ImageButton class="myButtonLink" ImageUrl="~/Images/empty_star.png" ID="rate3" runat="server" OnClick="rate3_Click"/>
                    <asp:ImageButton class="myButtonLink" ImageUrl="~/Images/empty_star.png" ID="rate4" runat="server" OnClick="rate4_Click"/>
                    <asp:ImageButton class="myButtonLink" ImageUrl="~/Images/empty_star.png" ID="rate5" runat="server" OnClick="rate5_Click"/>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Nedlastingslink">
                <ItemTemplate>
                    <asp:LinkButton ID="downloadbutton" runat="server" Text="Last ned" OnClick="Download_Click"
                        CommandArgument='<%# Eval("FileName") %>'></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Rapporter" ItemStyle-Font-Size="Small">
                <ItemTemplate>
                    <asp:LinkButton ID="reportbutton" runat="server" Text="Rapporter dokument" OnClick="Report_Click"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

以下是我尝试将评级值插入RatingTable的代码:

protected void updaterating(int rating)
    {
        //string value = SearchView.SelectedDataKey.Value.ToString();
        using (SqlConnection con = new SqlConnection(connectionstring))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO RatingTable (DocumentID, Rating) VALUES(@DocumentID, @Rating)"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.CommandType = CommandType.Text;
                    //cmd.Parameters.AddWithValue("@DocumentID", value);
                    cmd.Parameters.AddWithValue("@Rating", rating);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
        Response.Redirect(Request.Url.AbsoluteUri);
    }

    protected void rate1_Click(object sender, ImageClickEventArgs e)
    {
        updaterating(1);
    }

    protected void rate2_Click(object sender, ImageClickEventArgs e)
    {
        updaterating(2);
    }

    protected void rate3_Click(object sender, ImageClickEventArgs e)
    {
        updaterating(3);
    }

    protected void rate4_Click(object sender, ImageClickEventArgs e)
    {
        updaterating(4);
    }

    protected void rate5_Click(object sender, ImageClickEventArgs e)
    {
        updaterating(5);
    }

以下是RatingTable工具的内容:

[RatingTable] (
[DocumentID] INT     NOT NULL,
[Rating]     TINYINT NOT NULL,
PRIMARY KEY CLUSTERED ([DocumentID] ASC),
CONSTRAINT [FK_RatingTable_Documents] FOREIGN KEY ([DocumentID]) REFERENCES [dbo].[Documents] ([DocumentId])

);

我要做的是当我按下TemplateField“Rating”中的一个ImageButtons时,我希望它获取我所在行的当前DocumentID,并使用它将其插入到RatingTable中作为点击星号值的主键。在后面的代码中的更新函数中,我已经注释掉了一些行,我试图在GridView中使用DataKeyNames来获取ID,但这会给出一个空的GridView。

 if (!IsPostBack)
        {
            SearchView.DataKeyNames = new string[]{"DocumentID"};
            BindGrid();
        }

我添加了这个以尝试在绑定网格之前获取DataKeyNames,但GridView仍然是空的。

我还更改了字符串值,因为我使用了错误的属性:

protected void updaterating(int rating)
    {
        string value = SearchView.DataKeyNames.ToString();
        using (SqlConnection con = new SqlConnection(connectionstring))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO RatingTable (DocumentID, Rating) VALUES(@DocumentID, @Rating)"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@DocumentID", value);
                    cmd.Parameters.AddWithValue("@Rating", rating);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
        Response.Redirect(Request.Url.AbsoluteUri);
    }

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您需要在GridView中添加DataKeyName。如果我正确理解了这个问题,那就是DocumentID

<asp:GridView ID="SearchView" runat="server" 
    AutoGenerateColumns="false" 
    OnSelectedIndexChanged="SearchView_SelectedIndexChanged" 
    ShowHeaderWhenEmpty="true" 
    EmptyDataText="Ingen oppføringer"
    DataKeyNames="DocumentID">

然后当你运行这一行时:

string value = SearchView.SelectedDataKey.Value.ToString();

GridView实际上知道DataKey是什么。由于您使用的是SelectedDataKey,因此此属性的选定行也必须具有值。

要查找未选中行的索引,您需要找到包含该按钮的行。

protected void rate1_Click(object sender, ImageClickEventArgs e)
{
    ImageButton rate1 = (ImageButton)sender;
    GridViewRow row = (GridViewRow)rate1.NamingContainer;
    DataKey key = SearchView.DataKeys[row.DataItemIndex];

    // Now you have your key, use it how you'd like.
    // This may mean passing it as another variable
    // to your updaterating method.

    updaterating(1);
}