gpt4 book ai didi

c# - Gridview DataKey 的空引用异常

转载 作者:行者123 更新时间:2023-11-30 22:22:14 27 4
gpt4 key购买 nike

在这个网站上,我试图通过对 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>

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

最佳答案

如果要获取datakeyname

int index = Convert.ToInt32(e.CommandArgument);
string eventID = GridView1.DataKeys[index].Value.ToString()

关于c# - Gridview DataKey 的空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13949718/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com