我需要能够从GridView中删除记录,但为了做到这一点,我需要在.cs文件上的方法。问题是我有其他表与列表的ID相关联,所以如果删除命令失败,我需要显示错误消息。我的问题是,我只能在选择该记录时删除记录。 (GridView2。的 SelectedDataKey )。我希望能够在未选中时将其删除。
像GriView2.Datakey .....
aspx页面:
<LinkButton ID="LinkButton3" runat="server" CausesValidation="False"
CommandName="" Text="DELETE" OnClick ="del" >
.cs代码:
protected void del(object sender, EventArgs e)
{
string DeleteSql = "DELETE FROM [Trains] WHERE [ID_Train] = @ID_Train";
SqlCommand com = new SqlCommand(DeleteSql, Connection);
String key = GridView2.SelectedDataKey["ID_Train"].ToString();
try
{
com.Parameters.AddWithValue("@ID_Train", key);
cn.Open();
com.ExecuteNonQuery();
cn.Close();
Response.Redirect("Trains.aspx");
}
catch (Exception)
{
Label5.Text = "Error";
Label5.Visible = true;
}
}
答案 0 :(得分:1)
假设您有一个类似于此的模板构造:
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
你在SqlDataSource中有一个删除命令,你可以像这样处理delete命令并访问RowCommand事件中的数据键(注意我从VB转换了这个,所以C#可能会关闭,但你明白了):
private void GridView1_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e) Handles GridView1.RowCommand
{
if( e.CommandName == "Delete" ) {
string TrainID = GridView1.DataKeys(e.Row.RowIndex).Values("ID_Train");
integer rc = 0;
GridView1.DeleteParameters.Clear();
GridView1.DeleteParameters.Add("Train_ID", TrainId); // Adjust as necessary
try{
rc = GridView1.Delete();
if( rc == 1) {
// Deleted
} else {
// Not Deleted
}
}
catch() {
Label5.Text = "Error";
Label5.Visible = true;
}
}
}