2

在这个站点上,我试图通过在 gridview 行上的选择在数据库中插入一行。除了从 gridview 收集主键外,我一切都运行良好。我已经尝试了所有我能找到的都无济于事。到目前为止,我对这种语言还不是很好,但我的代码如下:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    string connectionString = ConfigurationManager.ConnectionStrings["sdsMicrosoftDB"].ConnectionString;
    OleDbConnection currentConnection = new OleDbConnection(connectionString);

    string eventID = GridView1.SelectedValue.ToString();

    try
    {
        string eid = Session["eid"].ToString();

        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandText = "INSERT INTO tblVolunteerRoster (eventID,empID) VALUES (@eventID,@empID)";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = currentConnection;

        cmd.Parameters.AddWithValue("@eventID", eventID);
        cmd.Parameters.AddWithValue("@empID", eid);
        currentConnection.Open();

        cmd.ExecuteNonQuery();
    }

特定于该 gridview 的代码是:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                DataSourceID="AccessDataSource1" CellPadding="4" ForeColor="#333333" 
                GridLines="None" HorizontalAlign="Center"
                onrowcommand="GridView1_RowCommand" DataKeyNames="eventID" >
                <AlternatingRowStyle BackColor="White" />

                <Columns>
                    <asp:CommandField ShowSelectButton="True" />
                    <asp:BoundField ApplyFormatInEditMode="True" DataField="eventID" 
                        HeaderText="Event ID" SortExpression="eventID" />
                    <asp:BoundField DataField="eventStartDate" HeaderText="Start Date" 
                        SortExpression="eventStartDate" DataFormatString="{0:MMM dd yyyy}" 
                        ApplyFormatInEditMode="True" />
                    <asp:BoundField DataField="eventDescription" HeaderText="Description" 
                        SortExpression="eventDescription" />
                    <asp:BoundField DataField="eventEstHours" HeaderText="Est. Hours" 
                        SortExpression="eventEstHours" />
                    <asp:BoundField DataField="eventLocation" HeaderText="Location" 
                        SortExpression="eventLocation" />
                    <asp:BoundField DataField="eventWorkersNeeded" HeaderText="Workers Needed" 
                        SortExpression="eventWorkersNeeded" />
              </Columns>

            </asp:GridView>

有任何想法吗?我已经把头撞在墙上试图自己弄清楚。提前致谢!

4

1 回答 1

3

如果要获取数据键名

int index = Convert.ToInt32(e.CommandArgument);
string eventID = GridView1.DataKeys[index].Value.ToString()
于 2012-12-19T10:00:54.133 回答