我正在尝试删除 gridview 中的项目,但删除命令正在 RowCommand 上再次执行。这是代码。该代码也在 RowDeleting 中,但它也在页面刷新时继续执行。有什么问题。对我提供的微小信息感到抱歉..我道歉。由于这里的字符数,现在这里是有限的代码
ASPX
<div id="griddiv" style="border: 1px solid #C0C0C0; top:170px; height:260px; width:830px; overflow:auto">
<asp:GridView ID="gvDetails" DataKeyNames="Item" runat="server"
AutoGenerateColumns="False" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
onrowdeleting="gvDetails_RowDeleting" ShowFooter="True" EnableViewState="true"
HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None"
BorderWidth="1px" CellPadding="4" EnableModelValidation="True"
GridLines="Horizontal" Width="797px" ForeColor="Black"
onrowcommand="gvDetails_RowCommand" onrowediting="gvDetails_RowEditing"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowupdating="gvDetails_RowUpdating"
onrowdatabound="gvDetails_RowDataBound" >
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdatexx" CommandName="Update" runat="server" ImageUrl="/Style%20Library/Images/save.png" ToolTip="Update" ValidationGroup="GridViewDataRowGroup"/>
<asp:ImageButton ID="imgbtnCancelxx" CommandName="Cancel" runat="server" ImageUrl="/Style%20Library/Images/cancel.png" ToolTip="Cancel" ValidationGroup="GridViewDataRowGroup" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEditxxxx" CommandName="Edit" runat="server" ImageUrl="/Style%20Library/Images/Edit.png" ToolTip="Edit" ValidationGroup="GridViewDataRowGroup" />
<asp:ImageButton ID="imgbtnDeletexx" CommandName="Delete" runat="server" OnClientClick="return confirm('Delete this Item ?');" ImageUrl="/Style%20Library/Images/delete.png" ToolTip="Delete" ValidationGroup="GridViewDataRowGroup" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAddxxxx" runat="server" CommandName="Insert" ImageUrl="/Style%20Library/Images/add.png" ToolTip="New Record" ValidationGroup="GridViewFooterRowGroup" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item">
<EditItemTemplate>
<%# Eval("ItemText")%>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemdesc" runat="server" Text='<%#Eval("ItemText") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDL_Items" runat="server" Width="230px" Font-Names="Verdana" Font-Size="12px" DataTextField="Description" DataValueField="INVENTORY_ITEM_ID" >
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<EditItemTemplate>
<asp:TextBox ID="txtQty" runat="server" Text='<%#Eval("Quantity") %>' BackColor="LightSkyBlue" ForeColor="Black" />
<asp:RequiredFieldValidator ID="rfvEditQty" runat="server" ControlToValidate="txtQty" Text="*" Display="Dynamic" ValidationGroup="GridViewDataRowGroup" />
<asp:RangeValidator ID="RvEditQty" runat="server" ErrorMessage="*" Type="Integer" MinimumValue="1" MaximumValue="999999" ControlToValidate="txtQty" Display="Dynamic" ForeColor="Red" ValidationGroup="GridViewDataRowGroup"></asp:RangeValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblQty" runat="server" Text='<%#Eval("Quantity") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrQty" runat="server" Text="0" />
<asp:RequiredFieldValidator ID="rfvQty" runat="server" ControlToValidate="txtftrQty" Text="*" Display="Dynamic" ValidationGroup="GridViewFooterRowGroup"/>
<asp:RangeValidator ID="RvFtrQty" runat="server" ErrorMessage="*" Type="Integer" MinimumValue="1" MaximumValue="999999" ControlToValidate="txtftrQty" Display="Dynamic" ForeColor="Red" ValidationGroup="GridViewFooterRowGroup" ></asp:RangeValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Needed-By">
<EditItemTemplate>
<asp:TextBox ID="txtNeededBy" runat="server" Text='<%#Eval("NeedBy") %>' BackColor="LightSkyBlue" ForeColor="Black" />
<asp:RequiredFieldValidator ID="reditNeededBy" runat="server" ControlToValidate="txtNeededBy" Text="*" Display="Dynamic" ValidationGroup="GridViewDataRowGroup" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblNeededBy" runat="server" Text='<%#Eval("NeedBy") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrNeededBy" runat="server" />
<asp:RequiredFieldValidator ID="rfvNeededBy" runat="server" ControlToValidate="txtftrNeededBy" Text="*" Display="Dynamic" ValidationGroup="GridViewFooterRowGroup" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
代码背后
public partial class EditPurchaseRequisitionUserControl : UserControl
{
public string reqId = "8";
string itemcat = "";
OraSPDataExchange.OraSPDataExchangeClient objServiceClient = new OraSPDataExchange.OraSPDataExchangeClient();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = new DataSet();
ds = objServiceClient.getItemCategories();
DD_ItemCategories.DataSource = ds;
DD_ItemCategories.DataTextField = "CATEGORY_DESCRIPTION";
DD_ItemCategories.DataValueField = "CATEGORY_ID";
DD_ItemCategories.DataBind();
btnSubmit.Enabled = false;
BindGridView();
fetchReqMaster();
fetchReqDetails();
}
}
protected void BindGridView()
{
//Declare a datatable for the gridview
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("ItemText");
dt.Columns.Add("Quantity");
dt.Columns.Add("NeedBy");
//Define a datarow for the datatable dt
DataRow dr = dt.NewRow();
//Now add the datarow to the datatable
dt.Rows.Add(dr);
gvDetails.DataSource = dt;
gvDetails.DataBind();
//Now hide the extra row of the grid view
gvDetails.Rows[0].Visible = false;
//Delete row 0 from the datatable
dt.Rows[0].Delete();
dt.AcceptChanges();
//View the datatable to the viewstate
ViewState["Data"] = dt;
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int itemid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values[0].ToString());
((DataTable)ViewState["Data"]).Rows[e.RowIndex].Delete();
((DataTable)ViewState["Data"]).AcceptChanges();
gvDetails.DataSource = (DataTable)ViewState["Data"];
gvDetails.DataBind();
DeleteGridItem(itemid);
//if (((DataTable)ViewState["Data"]).Rows.Count > 0)
//{
// gvDetails.DataSource = (DataTable)ViewState["Data"];
// gvDetails.DataBind();
//}
//else
//{
// DD_ItemCategories.Enabled = true;
// btnSubmit.Enabled = false;
// BindGridView();
//}
//gvDetails.DataSource = null;
//gvDetails.DataBind();
//DeleteGridItem(Convert.ToInt32(itemid));
//gvDetails.DataSource = (DataTable)ViewState["Data"];
//gvDetails.DataBind();
e.Cancel = true;
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
DropDownList DDItems = (DropDownList)gvDetails.FooterRow.FindControl("DDL_Items");
TextBox txtQty = (TextBox)gvDetails.FooterRow.FindControl("txtftrQty");
TextBox txtNeedBy = (TextBox)gvDetails.FooterRow.FindControl("txtftrNeededBy");
//Add the items to the gridview
DataTable dt = new DataTable();
//Assign the viewstate to the datatable
dt = (DataTable)ViewState["Data"];
DataRow dr = dt.NewRow();
dr["Item"] = DDItems.SelectedValue;
dr["ItemText"] = DDItems.SelectedItem.Text;
dr["Quantity"] = txtQty.Text;
dr["NeedBy"] = txtNeedBy.Text;
//Add the datarow to the datatable
dt.Rows.Add(dr);
if (((DataTable)ViewState["Data"]).Rows.Count > 0)
{
DD_ItemCategories.Enabled = false;
btnSubmit.Enabled = true;
}
//Now bind the datatable to the gridview
gvDetails.DataSource = dt;
gvDetails.DataBind();
//Add the details to viewstate also
ViewState["Data"] = dt;
}
//if (e.CommandName == "Delete")
//{
// int ind = Int32.Parse(e.CommandArgument.ToString());
// int itemID = Convert.ToInt32(gvDetails.DataKeys[ind].Values[0].ToString());
// ((DataTable)ViewState["Data"]).Rows[ind].Delete();
// ((DataTable)ViewState["Data"]).AcceptChanges();
// DeleteGridItem(itemID);
// gvDetails.DataSource = (DataTable)ViewState["Data"];
// gvDetails.DataBind();
//}
}
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
OraSPDataExchange.OraSPDataExchangeClient objServiceClient2 = new OraSPDataExchange.OraSPDataExchangeClient();
DataSet dsitems = new DataSet();
dsitems = objServiceClient2.getItems(Convert.ToInt32(DD_ItemCategories.SelectedValue));
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlDropDownList = (DropDownList)e.Row.FindControl("DDL_Items");
if (ddlDropDownList != null)
{
ddlDropDownList.DataSource = dsitems.Tables[0];
ddlDropDownList.DataTextField = "DESCRIPTION";
ddlDropDownList.DataValueField = "INVENTORY_ITEM_ID";
ddlDropDownList.DataBind();
ddlDropDownList.SelectedValue = gvDetails.DataKeys[e.Row.RowIndex].Values[0].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlDropDownList = (DropDownList)e.Row.FindControl("DDL_Items");
if (ddlDropDownList != null)
{
ddlDropDownList.DataSource = dsitems.Tables[0];
ddlDropDownList.DataTextField = "DESCRIPTION";
ddlDropDownList.DataValueField = "INVENTORY_ITEM_ID";
ddlDropDownList.DataBind();
ddlDropDownList.Items[0].Selected = true;
}
}
}
private int CheckUniqueData(int itemid)
{
for (int i = 0; i < gvDetails.Rows.Count; i++)
{
string itemval = gvDetails.Rows[0].Cells[0].Text;
if (Convert.ToInt32(itemval) == itemid)
return 1;
}
return 0;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Dictionary<string, int> retvalues = new Dictionary<string, int>();
int retvalues = CreateHeaderBlock();
//int dItemID = retvalues["vItemID"];
//int dItemCat = retvalues["vItemCatID"];
//CreateDetailBlock(dItemID, dItemCat);
Response.Write("<script>alert('Requisition submitted successfuly......'); window.location.href='http://portal.joshworld.local/SitePages/Home.aspx';</script>");
}
public int CreateHeaderBlock()
{
using (SPSite site = new SPSite("http://portal.joshworld.local/EFlowCenter"))
{
using (SPWeb Web = site.OpenWeb())
{
Web.AllowUnsafeUpdates = true;
// Open List
SPList list = Web.Lists["Requisition_Master"];
// Add new item in List
SPListItem item = list.Items.Add();
item["Request ID"] = "";
item["Requester"] = lbl_Rname.Text;
item["Email"] = lbl_REmail.Text;
item["Department"] = lbl_RDept.Text;
item["Location"] = lbl_RLocation.Text;
item["Header_ItemCategory"] = DD_ItemCategories.SelectedItem.Text;
item["Header_Remarks"] = txtRemarks.Text;
item.Update();
// Get Item ID
int reqId = item.ID;
SPListItem uitem = list.GetItemById(reqId);
uitem["Request ID"] = reqId.ToString();
uitem.Update();
Web.AllowUnsafeUpdates = false;
// Dictionary<string, int> values = new Dictionary<string, int>();
// values.Add("vItemID", listItemId);
// values.Add("vItemCatID", Convert.ToInt32(DD_ItemCategories.SelectedValue));
// values.Add("hRequester", lbl_Rname.Text);
// values.Add("hLocation",lbl_RLocation.Text);
CreateDetailBlock(reqId, lbl_Rname.Text, lbl_RLocation.Text, Convert.ToInt32(DD_ItemCategories.SelectedValue), txtRemarks.Text);
return 1;
}
}
}
private void CreateDetailBlock(int headerreqID, string headerrequester, string headerloc, int headerItemCategory, string headerRemarks)
{
using (SPSite site = new SPSite("http://portal.joshworld.local/EFlowCenter"))
{
using (SPWeb Web = site.OpenWeb())
{
//Web.AllowUnsafeUpdates = true;
// Open List
SPList list = Web.Lists["Requisition_Detail"];
//Loop through GridView Items
foreach (GridViewRow rowItem in gvDetails.Rows)
{
// Find Controls and read values here
string KeyItemID = gvDetails.DataKeys[rowItem.RowIndex].Values["Item"].ToString();
Label lblitemdesc = (Label)rowItem.FindControl("lblitemdesc");
Label lblitemqty = (Label)rowItem.FindControl("lblQty");
Label lblNeedBy = (Label)rowItem.FindControl("lblNeededBy");
Web.AllowUnsafeUpdates = true;
// Add new item in List
SPListItem item = list.Items.Add();
item["Request ID"] = headerreqID;
item["Header_Requester"] = headerrequester;
item["Header_Location"] = headerloc;
item["Item ID"] = Convert.ToInt32(KeyItemID);
item["Item Description"] = lblitemdesc.Text;
item["Quantity"] = Convert.ToInt32(lblitemqty.Text);
item["Needed_By"] = lblNeedBy.Text;
item["Header_Remarks"] = headerRemarks;
item.Update();
Web.AllowUnsafeUpdates = false;
}
}
}
}
private void setPortalUserInformation(string portalUser)
{
lbl_ROpUnit.Text = portalUser;
using (SPSite site = new SPSite("http://portal.joshworld.local/EFlowCenter"))
{
using (SPWeb Web = site.OpenWeb())
{
//Web.AllowUnsafeUpdates = true;
// Open List
SPList list = Web.Lists["Req Approval Hierarchy"];
//SPListItem myItems = list.GetItemByIdSelectedFields(5, "EMAIL ADDRESS");
//SPListItem item = null;
//SPQuery query = new SPQuery();
const string camlQuery = @"<Query><Where><Eq><FieldRef Name='EMAIL_x0020_ADDRESS' /><Value Type='Text'>zahid.zia@samba.com.pk</Value> </Eq> </Where></Query>";
SPQuery query = new SPQuery();
query.Query = camlQuery;
// Retrieving the data from the List
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem objListItem in items)
{
lbl_Rname.Text = objListItem["Title"].ToString();
}
}
}
}
private void showinfo(string portal_user)
{
string camlQuery = @"<Where><Eq><FieldRef Name='EMAIL_x0020_ADDRESS' /><Value Type='Text'>" + portal_user + "</Value></Eq></Where>";
using (SPSite objSite = new SPSite("http://portal.joshworld.local/EFlowCenter"))
{
using (SPWeb objWeb = objSite.OpenWeb())
{
// Building a query
SPQuery query = new SPQuery();
query.Query = camlQuery;
// Retrieving the data from the List
SPList objList = objWeb.Lists["Requisition Hierarchy"];
SPListItemCollection items = objList.GetItems(query);
int licount = items.Count;
if (licount == 0)
lbl_Rname.Text = "Zero";
else
lbl_Rname.Text = licount.ToString();
foreach (SPListItem objListItem in items)
{
lbl_Rname.Text = objListItem["Title"].ToString();
lbl_RLocation.Text = objListItem["LOCATION"].ToString();
lbl_RDept.Text = objListItem["DEPARTMENT_x0020_NAME"].ToString();
lbl_REmail.Text = objListItem["EMAIL_x0020_ADDRESS"].ToString();
}
DD_ItemCategories.Items.FindByText(itemcat).Selected = true;
}
}
}
protected string ClearDomain(string sItem)
{
int sLoc = (sItem.IndexOf("\\") + 1);
string sOutPut;
sOutPut = sItem.Substring(sLoc);
return sOutPut;
}
private void fetchReqMaster()
{
string camlQuery = @"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + reqId + "</Value></Eq></Where>";
using (SPSite objSite = new SPSite("http://portal.joshworld.local/EFlowCenter"))
{
using (SPWeb objWeb = objSite.OpenWeb())
{
// Building a query
SPQuery query = new SPQuery();
query.Query = camlQuery;
// Retrieving the data from the List
SPList objList = objWeb.Lists["Requisition_Master"];
SPListItemCollection items = objList.GetItems(query);
foreach (SPListItem objListItem in items)
{
lbl_Rname.Text = objListItem["Requester"].ToString();
lbl_RLocation.Text = objListItem["Location"].ToString();
lbl_RDept.Text = objListItem["Department"].ToString();
lbl_REmail.Text = objListItem["Email"].ToString();
DD_ItemCategories.ClearSelection();
itemcat = objListItem["Header_ItemCategory"].ToString();
}
DD_ItemCategories.Items.FindByText(itemcat).Selected = true;
}
}
}
private void fetchReqDetails()
{
gvDetails.DataSource = null;
gvDetails.DataBind();
string camlQuery = @"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + reqId + "</Value></Eq></Where>";
using (SPSite objSite = new SPSite("http://portal.joshworld.local/EFlowCenter"))
{
using (SPWeb objWeb = objSite.OpenWeb())
{
// Building a query
SPQuery query = new SPQuery();
query.Query = camlQuery;
// Retrieving the data from the List
SPList objList = objWeb.Lists["Requisition_Detail"];
SPListItemCollection items = objList.GetItems(query);
//Add the items to the gridview
DataTable dtx = new DataTable();
//Assign the viewstate to the datatable
dtx = (DataTable)ViewState["Data"];
foreach (SPListItem objListItem in items)
{
DataRow dr = dtx.NewRow();
dr["Item"] = objListItem["Item_x0020_ID"].ToString();
dr["ItemText"] = objListItem["Item_x0020_Description"].ToString();
dr["Quantity"] = objListItem["Quantity"].ToString();
dr["NeedBy"] = objListItem["Needed_By"].ToString();
//Add the datarow to the datatable
dtx.Rows.Add(dr);
//Add the details to viewstate also
ViewState["Data"] = dtx;
}
//BindGridView();
if (((DataTable)ViewState["Data"]).Rows.Count > 0)
{
DD_ItemCategories.Enabled = false;
btnSubmit.Enabled = true;
}
//Add the items to the gridview
DataTable dtgrid = new DataTable();
//Assign the viewstate to the datatable
dtgrid = (DataTable)ViewState["Data"];
//Now bind the datatable to the gridview
gvDetails.DataSource = dtgrid;
gvDetails.DataBind();
}
}
}
public void DeleteGridItem(int gridItemId)
{
string camlQuery = @"<Where><Eq><FieldRef Name='Item_x0020_ID' /><Value Type='Text'>" + gridItemId + "</Value></Eq></Where>";
using (SPSite objSite = new SPSite("http://portal.joshworld.local/EFlowCenter"))
{
using (SPWeb objWeb = objSite.OpenWeb())
{
objWeb.AllowUnsafeUpdates = true;
// Building a query
SPQuery query = new SPQuery();
query.Query = camlQuery;
// Retrieving the data from the List
SPList objList = objWeb.Lists["Requisition_Detail"];
SPListItemCollection items = objList.GetItems(query);
items.Delete(0);
objWeb.AllowUnsafeUpdates = false;
}
}
}
}