Reputation: 29
With this site, I am attempting to insert a row in a database through a selection on a gridview row. I've got everything working well except for collecting the primary key from the gridview. I've tried all I can find to no avail. I'm not great with this language as of yet, but my code is below:
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();
}
The code specific to that gridview is:
<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>
Any ideas? I've beat my head against a wall trying to figure it out on my own. Thanks in advance!
Upvotes: 2
Views: 2206
Reputation: 1082
If you want to get the datakeyname
int index = Convert.ToInt32(e.CommandArgument);
string eventID = GridView1.DataKeys[index].Value.ToString()
Upvotes: 3