【发布时间】:2021-12-27 07:51:30
【问题描述】:
我正在尝试从网格中删除一条记录。情况是,我首先只使用gridview中的链接按钮从网格中删除记录,然后用户可以单击gridview上的外部按钮,然后必须从数据库中删除记录。 问题是,首先从网格中删除记录将使该特定记录在单击外部按钮后无法删除。 我已附上代码,请查看!
**Aspx file:**
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CountryService.aspx.cs"
Inherits="CountryServiceApp.CountryService" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Country Website</title>
<link href="css/bootstrap-grid.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap-grid.min.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap-reboot.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap-reboot.min.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<a href="CountryService.aspx"></a>
<script src="js/bootstrap.bundle.js" type="text/javascript"></script>
<script src="js/bootstrap.bundle.min.js" type="text/javascript"></script>
<script src="js/bootstrap.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container my-4">
<form id="form1" runat="server">
<section id="mian-content">
<section id="wrapper">
<section>
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
<div class=" col-md-4 col-md-offset-4 text-center ml-3" style="text-align:center" >
<h3>Country and Cities Page</h3>
</div>
</header>
<div class="panel-body">
<div class="container my-5">
<div class="row">
<div class="col-md-5 col-md-offset-1">
<div class="form-group">
<asp:Label ID="Label1" Text="Country Code" runat="server" class="form-label"/>
<asp:TextBox runat="server" Enabled="true" CssClass="form-control input-sm" placeholder="Enter Country Code" ID="txCountryCode"/>
</div>
</div>
<div class="col-md-5 col-md-offset-1">
<div class="form-group">
<asp:Label ID="Label2" Text="Country Name" runat="server" class="form-label"/>
<asp:TextBox runat="server" Enabled="true" CssClass="form-control input-sm" ID="txtCountryName"/>
</div>
<br />
<br />
<%--onDelete--%>
<%--btnDelete_Click --%>
<asp:Button ID="btnFind" runat="server" Text="Find" CssClass="btn btn-info"
onclick="btnFind_Click"/>
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btn btn-primary"
onclick="btnSave_Click"/>
<asp:Button ID="btnDelete" runat="server" Text="Delete"
CssClass="btn btn-danger" onclick="onDelete" OnClientClick="" />
<asp:Button ID="btnUpdate" runat="server" Text="Update"
CssClass="btn btn-warning" onclick="btnUpdate_Click"/>
<asp:Button ID="btnCancel" runat="server" Text="Cancel"
CssClass="btn btn-primary" onclick="btnCancel_Click"/>
<br />
<br />
</div>
</div>
</div>
</div>
</section>
</div>
</div>
<br />
<br />
<%-- OnRowDataBound = "OnRowDataBound" --%>
<%-- onrowupdating="gridCity_RowUpdating" --%>
<asp:GridView ID="gridCity" runat="server"
GridLines="Vertical"
RowHeaderColumn="Action"
onrowdeleting="gridCity_RowDeleting"
CssClass="table table-bordered table-dark"
DataKeyNames="CityCode"
onrowediting="gridCity_RowEditing"
AutoGenerateEditButton="false" onrowcancelingedit="gridCity_RowCancelingEdit"
>
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server"></asp:CheckBox>
<asp:LinkButton ID="btnEdit" runat="server" Text="Edit"
CssClass="btn btn-warning" CommandName="Edit"></asp:LinkButton>
<asp:Button ID="btnDeleteGrid" runat="server" Text="Delete"
CssClass="btn btn-danger" CommandName="Delete"></asp:Button>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Update" runat="server" CssClass="btn btn-warning" OnClick="OnUpdate" CommandName="Update"/>
<asp:LinkButton ID="LinkButton2" Text="Cancel" runat="server" CssClass="btn btn-primary" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#DCDCDC" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</section>
</section>
</section>
</form>
</div>
</body>
</html>
**Aspx.Cs file:**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace CountryServiceApp
{
public partial class CountryService : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnCancel.Enabled = false;
btnDelete.Enabled = false;
btnSave.Enabled = false;
btnUpdate.Enabled = false;
}
}
protected void btnFind_Click(object sender, EventArgs e)
{
try
{
countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
countryService.Country c = client.Search(txCountryCode.Text);
if (c != null)
{
txtCountryName.Text = c.CountryName;
loadData();
btnCancel.Enabled = true;
btnDelete.Enabled = true;
btnSave.Enabled = true;
btnUpdate.Enabled = true;
btnFind.Enabled = true;
}
else
{
Response.Write("Record does not exist");
}
}
catch (Exception)
{
Response.Write("Record does not exist");
}
}
protected void loadData()
{
DataTable dt = new DataTable();
gridCity.Visible = true;
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spSelectCountryandCity", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameterId = new SqlParameter();
parameterId.ParameterName = "@CountryCode";
parameterId.Value = txCountryCode.Text;
cmd.Parameters.Add(parameterId);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
//while (rdr.Read())
//{
// gridCity.DataSource = rdr;
// gridCity.DataBind();
//}
if (rdr.HasRows)
{
dt.Load(rdr);
gridCity.DataSource = dt;
gridCity.DataBind();
ViewState["gridData"] = dt;
}
else
{
gridCity.Visible = false;
}
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
txCountryCode.Text = txtCountryName.Text = string.Empty;
gridCity.Visible = false;
btnCancel.Enabled = false;
btnDelete.Enabled = false;
btnSave.Enabled = false;
btnUpdate.Enabled = false;
btnFind.Enabled = true;
}
protected void gridCity_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = (DataTable)ViewState["gridData"];
if (dt.Rows.Count > 0)
{
//DataRow index = dt.Rows[e.RowIndex];
//Session["index"] = index;
CheckBox chkSelect = (CheckBox)gridCity.Rows[e.RowIndex].FindControl("chkSelect");
if (chkSelect.Checked == true)
{
Session["chkSelect"] = chkSelect;
// cityCode = Convert.ToString(gridCity.Rows[e.RowIndex].Cells[1].Text);
}
dt.Rows[e.RowIndex].Delete();
dt.AcceptChanges();
gridCity.DataSource = dt;
gridCity.DataBind();
}
//txCountryCode.Text = txtCountryName.Text = string.Empty;
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
countryService.Country c = new countryService.Country();
c.CountryCode = txCountryCode.Text;
c.CountryName = txtCountryName.Text;
client.Insert(c);
Response.Write("Country added in a table");
loadData();
btnFind.Enabled = true;
}
catch (Exception)
{
Response.Write("Record already exist");
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
client.Delete(txCountryCode.Text);
Response.Write("Record of " + " " + txtCountryName.Text + " " + "Cities has been deleted");
loadData();
btnFind.Enabled = true;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
countryService.Country c = new countryService.Country();
c.CountryCode = txCountryCode.Text;
c.CountryName = txtCountryName.Text;
client.Update(c);
Response.Write("Country updated in a table");
loadData();
btnFind.Enabled = true;
}
protected void gridCity_RowEditing(object sender, GridViewEditEventArgs e)
{
gridCity.EditIndex = e.NewEditIndex;
//loadData();
}
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
//string CityCode=((TextBox)row.Cells[1].Controls[0]).Text;
string CityName = ((TextBox)row.Cells[2].Controls[0]).Text;
//string CountryCode = ((TextBox)row.Cells[3].Controls[0]).Text;
DataTable dt = ViewState["gridData"] as DataTable;
//dt.Rows[row.RowIndex]["CityCode"] = CityCode;
if (CityName != null && CityName != "")
{
dt.Rows[row.RowIndex]["CityName"] = CityName;
//dt.Rows[row.RowIndex]["CountryCode"] = CountryCode;
//dt.AcceptChanges();
//dt.Rows[row.RowIndex].SetModified();
ViewState["gridData"] = dt;
gridCity.EditIndex = -1;
gridCity.DataSource = dt;
gridCity.DataBind();
}
else
{
Response.Write("Name field can not be empty");
}
}
protected void gridCity_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridCity.EditIndex = -1;
loadData();
}
protected void onDelete(object sender, EventArgs e)
{
// foreach (GridViewRow grow in gridCity.Rows)
// {
// Button btn = (Button)grow.FindControl("btnDeleteGrid");
// //GridViewRow row = (sender as Button).NamingContainer as GridViewRow;
// DataTable dt = (DataTable)Session["index"];
// if (grow.RowIndex == 0)
// {
// //Convert.ToString(grow.Cells[1].Text);
// string cityCode = Convert.ToString(dt.Rows[1]["CityCode"]);
// countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
// client.DeleteCity(cityCode);
// }
// else
// {
// Response.Write("Error");
// }
// }
// //Displaying the Data in GridView
// loadData();
// btnFind.Enabled = true;
//}
DataTable dt = (DataTable)ViewState["gridData"];
gridCity.DataSource = dt;
gridCity.DataBind();
string cityCode = null;
for (int i = 0; i <gridCity.Rows.Count ; i++)
{
CheckBox chkSelect = (CheckBox)gridCity.Rows[i].FindControl("chkSelect");
chkSelect.Checked = true;
//CheckBox chkSelect = (CheckBox)Session["chkSelect"];
if (chkSelect.Checked == true)
{
cityCode = Convert.ToString(gridCity.Rows[i].Cells[1].Text);
countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
client.DeleteCity(cityCode);
}
}
loadData();
Response.Write("Record Deleted");
}
}
}
【问题讨论】:
-
也许你可以看看this post并找到解决方案。