每当我从gridview中删除我选择删除的行时,上面所选行的行都会被删除。不知道为什么。请参阅我的删除代码。
<asp:GridView ID="grdPostData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False" AllowPaging="true" PageSize="10" CssClass="hoverTable" OnPageIndexChanging="grdPostData_PageIndexChanging" OnRowDataBound="grdPostData_RowDataBound" OnRowDeleting="grdPostData_RowDeleting" DataKeyNames="Id">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:BoundField DataField="description" HeaderText="Description" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandArgument='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
</asp:GridView>
您的参考代码背后: -
protected void grdPostData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
bool IsDeleted = false;
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "DELETE FROM tbl_Post WHERE Id=@Id";
cmd.Parameters.AddWithValue("@Id", Id);
cmd.Connection = conn;
conn.Open();
IsDeleted = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
}
if (IsDeleted)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Page Succesfully deleted');window.location ='csrposts.aspx';", true);
grdPostData.DataBind();
}
else
{
Response.Write("Some error");
}
}
请让我知道我哪里出错了。我尝试调试代码,而Id正在使用0
。
Gridview bindinf代码: -
public void BindGrid()
{
string strQuery = "Select Id, title, description, Active from tbl_Post Order by ID desc";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
grdPostData.DataSource = dt;
grdPostData.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
try
{
conn.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
sda.Dispose();
conn.Dispose();
}
}
答案 0 :(得分:1)
更新了解决方案。完全正常工作。我在DataBound中创建这些文本框,并在if条件下检查Gridview是否为空。
如果Gridview为空,则不会创建HeaderRow,以便Gridview和Page能够显示,否则将显示HeaderRow。
希望这对你有用。
的aspx: -
<%@ Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true"
CodeFile="csrposts.aspx.cs" Inherits="CSRProject.csrposts" %>
<asp:GridView ID="grdPostData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;"
CellPadding="3" AutoGenerateColumns="False" AllowPaging="true" PageSize="4" CssClass="hoverTable"
OnPageIndexChanging="grdPostData_PageIndexChanging" OnDataBound="grdPostPageData_DataBound"
OnRowDataBound="grdPostData_RowDataBound" DataKeyNames="Id" OnRowDeleting="grdPostData_RowDeleting"
OnRowEditing="grdPostData_RowEditing" OnRowUpdating="grdPostData_RowUpdating"
OnRowCancelingEdit="grdPostData_RowCancelingEdit">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:BoundField DataField="description" HeaderText="Description" ItemStyle-Width="30"
ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:LinkButton ID="lbltbDelete" runat="server" OnClick="lbltbDelete_Click" Text="Delete"
OnClientClick="return confirm('Are you sure you want to delete this record?')"
CausesValidation="false" />
<asp:ImageButton ID="btnDelete" AlternateText="Delete" CommandName="Delete" ImageUrl="~/images/delete.png"
runat="server" Width="15" Height="15" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png"
ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png"
UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
<EmptyDataTemplate>
No Result Found
</EmptyDataTemplate>
</asp:GridView>
Aspx.cs
protected void grdPostPageData_DataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdPostData.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdPostData.Columns[i].HeaderText;
txtSearch.CssClass = "form-control HaydaBre";
cell.Controls.Add(txtSearch);
row.Controls.Add(cell);
}
if (grdPostData.Rows.Count > 0)
{
grdPostData.HeaderRow.Parent.Controls.AddAt(0, row);
}
else
{
}
}
protected void grdPostData_RowDataBound(object sender, GridViewRowEventArgs e)
{
/*
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdPostData.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdPostData.Columns[i].HeaderText;
txtSearch.CssClass = "form-control HaydaBre";
cell.Controls.Add(txtSearch);
row.Controls.Add(cell);
}
grdPostData.HeaderRow.Parent.Controls.AddAt(-1, row);
// e.Row.Parent.Controls.AddAt(1, row);
}
*/
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from tbl_PostCategory ", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList DropDownList1 =
(DropDownList)e.Row.FindControl("ddlPostCategory");
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "cat_title";
DropDownList1.DataValueField = "cat_title";
DropDownList1.DataBind();
}
}
}
行删除代码相同。
答案 1 :(得分:0)
您的代码看起来不错。希望它不是数据库中的问题。试试这个 将其添加到Gridview
OnRowCommand="GridView_RowCommand"
CodeBehing: -
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Delete")
{
// Get the value of command argument
int Id= convert.ToInt32(e.CommandArgument);
// Do whatever operation you want.
}
}
可替换地: - 在删除的图像按钮上添加onclick事件并尝试此
protected void ImageButton_Click(object sender, EventArgs e)
{
ImageButton btn = sender as ImageButton;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
int id =Convert.ToInt32((gRow.FindControl("lblId") as Label).Text);
}
更新: - 将您的itemtemplate更改为此
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>' </asp:Label>
</ItemTemplate>
</asp:TemplateField>
因此,下拉列表旁边会显示提取的ID。确保其显示正确的值