【问题标题】:Get current id in GridView and insert it as id in another table on button click在 GridView 中获取当前 id,并在单击按钮时将其作为 id 插入另一个表中
【发布时间】:2015-07-21 21:44:07
【问题描述】:

我有一个名为 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作为主键,点击的星号的值。在后面代码的 updaterating 函数中,我已经注释掉了一些我尝试在 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);
    }

非常感谢任何帮助!

【问题讨论】:

  • 您并没有真正告诉我们您的代码的哪一部分没有按预期工作以及您的问题到底是什么。
  • 后面代码中的字符串值和 DocumentID 的 AddWithValue 是我在 GridView 中使用 DataKeyNames 作为 DocumentID 尝试的,但是 GridView 不会显示任何内容。
  • 对不起。当我单击其中一个按钮时,我收到一个 SQLException,因为未声明 @DocumentID。但我不确定如何获取 DocumentID 并插入它。
  • 您能否编辑您的问题并添加这些详细信息以及您遇到的确切异常?

标签: sql asp.net gridview sqlcommand


【解决方案1】:

您需要将DataKeyName 添加到您的GridView。如果我正确理解了这个问题,那就是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);
}

【讨论】:

  • 当我在 GridView 中有 DataKeyNames 时,GridView 是空的。我还将 SelectedDataKey 更改为 SearchView.DataKeyNames.ToString();
  • 使用SearchView.DataKeyNames.ToString(); 也不起作用,因为DataKeyNames 是一个字符串数组。您需要在 DataKeyNames 数组中找到行的索引以获取其值。
  • 添加 DataKeyName 不会导致没有数据绑定到 GridView。如果数据源中不存在DataKeyName,则会出现错误。
  • 我明白了。关于如何找到索引的任何建议?我对使用 ASP.Net 不是很有经验。
  • 我在 updaterating 函数中添加了一个字符串参数。但行 DataKey key = SearchView.DataKeyNames[row.DataItemIndex];给出错误:无法将类型“字符串”隐式转换为“System.Web.UI.WebControls.DataKey”
猜你喜欢
  • 1970-01-01
  • 2021-08-25
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-21
  • 2018-06-15
  • 1970-01-01
相关资源
最近更新 更多