使用gridview rowcommand buttonfield向sql添加记录

时间:2015-03-26 18:23:51

标签: c# sql asp.net .net

我尝试在课程gridview的每一行添加注册按钮,以便当用户点击该特定行上的注册按钮时,它会注册通过在sql中添加课程注册记录,他可以在该行的特定课程中学习。

我应该如何编写代码以将该行的数据插入sql?

C#:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Register")
    {
        int index = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = GridView1.Rows[index];
    }

ASP.NET:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
        ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
        OnRowCommand="GridView1_RowCommand" Width="394px">
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" />
            <asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True"></asp:BoundField>
            <asp:BoundField DataField="SpeakerName" HeaderText="Speaker" ReadOnly="True" />
            <asp:BoundField DataField="startdate" HeaderText="Date" ReadOnly="True" />
            <asp:BoundField DataField="Capacity" HeaderText="Capacity" />
            <asp:TemplateField HeaderText="Button" ShowHeader="False">
                <ItemTemplate>
                    <asp:Button ID="RegButton" runat="server" CausesValidation="false" CommandName="Register"
                        CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Register" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField HeaderText="Select" SelectText="Details" ShowSelectButton="True" />
        </Columns>
        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
        <SortedAscendingCellStyle BackColor="#FDF5AC" />
        <SortedAscendingHeaderStyle BackColor="#4D0000" />
        <SortedDescendingCellStyle BackColor="#FCF6C0" />
        <SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>

1 个答案:

答案 0 :(得分:0)

首先,您应该将Id(主键)添加为datakeynames property GridView1,然后Id GridView1_RowCommand,如下所示:< / p>

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Register")
    {
        GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
        int courseId = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
        //your other codes
    }

所以,你有你的课程Id,通过选择你可以将当前记录添加到sql.hope的记录,它会有所帮助。

编辑:

此外,您不再需要在您的aspx页面中使用此部分CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"