更新或插入时返回gridview的主键(ASP.NET,C#)
我需要对要审核的表进行所有更改,例如插入、更新和删除,并且我使用一个简单的SQLDataSource和GridView,以及自动生成的INSERT/UPDATE/DELETE语句。问题是,当一行被更新时,我想获取ID(主键)并将其放入审核表中——但因为更新查询的唯一参数是实际数据而不是主键,所以我不知道如何访问此信息。以下是我的更新查询:更新或插入时返回gridview的主键(ASP.NET,C#),c#,asp.net,sqldatasource,auditing,C#,Asp.net,Sqldatasource,Auditing,我需要对要审核的表进行所有更改,例如插入、更新和删除,并且我使用一个简单的SQLDataSource和GridView,以及自动生成的INSERT/UPDATE/DELETE语句。问题是,当一行被更新时,我想获取ID(主键)并将其放入审核表中——但因为更新查询的唯一参数是实际数据而不是主键,所以我不知道如何访问此信息。以下是我的更新查询: InsertCommand="INSERT INTO [NominalCode] ([VAXCode], [Reference], [CostCentre],
InsertCommand="INSERT INTO [NominalCode] ([VAXCode], [Reference], [CostCentre], [Department], [ReportingCategory]) VALUES (@VAXCode, @Reference, @CostCentre, @Department, @ReportingCategory)"
下面是审核的代码:
protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
string fields = e.Command.Parameters[0].Value.ToString() + "," + e.Command.Parameters[1].Value.ToString() + "," + e.Command.Parameters[2].Value.ToString() + "," + e.Command.Parameters[3].Value.ToString() + "," + e.Command.Parameters[4].Value.ToString();
System.Security.Principal. WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
string[] namearray = p.Identity.Name.Split('\\');
string name = namearray[1];
string queryString = "INSERT INTO Audit (source, action, item, userid, timestamp) VALUES (@source, @action, @item, @userid, @timestamp)";
using (SqlConnection connection = new SqlConnection("con string removed for privacy"))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@source", "Nominal");
command.Parameters.AddWithValue("@action", "Update");
command.Parameters.AddWithValue("@item", fields);
command.Parameters.AddWithValue("@userid", name);
command.Parameters.AddWithValue("@timestamp", DateTime.Now);
connection.Open();
try
{
command.ExecuteNonQuery();
}
catch (Exception x)
{
Response.Write(x);
}
finally
{
connection.Close();
}
}
}
好吧,我觉得自己很愚蠢。ID当然位于SQL查询的WHERE子句中!出于某种原因,我粘贴了INSERT命令