【发布时间】:2012-12-19 09:57:35
【问题描述】:
在这个网站上,我试图通过对 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();
}
特定于该网格视图的代码是:
<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>
有什么想法吗?我已经把头撞在墙上试图自己弄清楚。提前致谢!
【问题讨论】:
-
有什么问题?你期待什么,会发生什么,你尝试了什么?显示确切的错误消息及其出现的行。
-
您必须处理
SelectedIndexChanged事件而不是RowCommand才能使用GridView1.SelectedValue属性返回键值。 -
我在以下行收到一个空引用错误:string eventID = GridView1.SelectedValue.ToString(); (第一个代码块,第 6 行)我希望它从单击“选择”的 GridView 行中提取事件 ID,但它所做的只是抛出此错误。以前的尝试导致值 -1,由于参照完整性,我的访问数据库不允许这样做。