C# GridView 删除行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15403231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:41:20  来源:igfitidea点击:

GridView Delete Row

c#gridviewdatatable

提问by Kerieks

I'm trying to delete a row in a gridview (the data is not in the database yet), so it should be a simple delete row, if anybody can please point me in the right direction.... This is what I have done:

我正在尝试删除 gridview 中的一行(数据还没有在数据库中),所以它应该是一个简单的删除行,如果有人可以指出我正确的方向......这就是我所拥有的完毕:

     else if (e.CommandName == "DeletePart")
    {
        int index = Convert.ToInt32(e.CommandArgument); //#1 line
        GridView1.DeleteRow(index);  //#2 line
    }

The error that I am receiving is : "Input string was not in a correct format." (this happens on #1 line)...

我收到的错误是:“输入字符串的格式不正确。” (这发生在#1 行)...

This is how the gridview looks like: (use a linkbutton to do the delete)

这是 gridview 的样子:(使用链接按钮进行删除)

    <asp:GridView ID="GridView1" runat="server"  AllowPaging="True" 
                                EmptyDataText="No parts has been added to the model, please add a part."
                                BorderColor="Black" BorderStyle="Solid"  BorderWidth="2px" 
                                CellPadding="3" onrowcommand="GridView1_RowCommand" 
                            onrowediting="GridView1_RowEditing" onrowdeleting="GridView1_RowDeleting">
                                <Columns>
                                <asp:TemplateField HeaderText="">
                                 <ItemTemplate>
                                   <asp:LinkButton ID="EditButton" runat="server" CssClass="EditButton" CommandName="Edit" Text="Edit" />
                                 </ItemTemplate>
                                 </asp:TemplateField>
                                 <asp:TemplateField HeaderText="">
                                 <ItemTemplate>
                                   <asp:LinkButton ID="DeleteButton" runat="server" CssClass="DeleteButton" CommandName="DeletePart" CommandArgument='<%# Container.DataItemIndex %>' Text="Delete" />
                                 </ItemTemplate>
                                 </asp:TemplateField>
                                </Columns>
                            <HeaderStyle BackColor="#FFFFCC"  BorderColor="Black" BorderStyle="Solid" 
                                BorderWidth="2px" />
                        </asp:GridView>

Class of how the gridview populated and binded:

gridview 如何填充和绑定的类:

     public int companyID = 0;
public int methodID = 0;
DataTable dt;
#region SQLConnections

string connectionString = ConfigurationManager.ConnectionStrings["SOSConnectionString"].ConnectionString;
SqlConnection conn;
#endregion

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        dt = new DataTable();
        MakeDataTable();
        EmptyDataString();
    }
    else
    {
        dt = (DataTable)ViewState["DataTable"];
    }
    ViewState["DataTable"] = dt; 

}

#region GridView

private void EmptyDataString()
{
    TemplateBuilder tmpEmptyDataTemplate = new TemplateBuilder();
    tmpEmptyDataTemplate.AppendLiteralString("No parts has been added to the model, please add a part.");
    GridView1.EmptyDataTemplate = tmpEmptyDataTemplate;
    GridView1.DataBind();
}

private void MakeDataTable()
{
    dt.Columns.Add("Item");
    dt.Columns.Add("Quantity");
    dt.Columns.Add("Price P/Quantity");
}

private void AddToDataTable()
{
    DataRow dr = dt.NewRow();
    dr["Item"] = txtPart.Text;
    dr["Quantity"] = numQuantity.Text;
    dr["Price P/Quantity"] = txtPricePQ.Text;
    dt.Rows.Add(dr);
}

private void BindGrid()
{
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

protected void btnAddPart_Click(object sender, EventArgs e)
{
    AddToDataTable();
    BindGrid();
    ClearNewParts();
}
#endregion

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Edit")
    { 
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
            txtPart.Text = row.Cells[2].Text;
            numQuantity.Text = row.Cells[3].Text;
            txtPricePQ.Text = row.Cells[4].Text;
        }
    }
    else if (e.CommandName == "DeletePart")
    {
        //int iCount = GridView1.Rows.Count;
        //for (int i = 1; i <= iCount; i++)
        //{
        //    GridView1.DeleteRow(i);
        //}
      //  int rowIndex = Convert.ToInt32(GridView1.SelectedRow);

        int index = Convert.ToInt32(e.CommandArgument);
        GridView1.DeleteRow(index);

        //int index = Convert.ToInt32(e.CommandArgument);
        //GridView1.DeleteRow(rowIndex);
    }


    GridView1.DataBind();
}

采纳答案by Kerieks

Found the solution, only needed to do a databound.... Here is the working code:

找到了解决方案,只需要做一个数据绑定......这是工作代码:

    else if (e.CommandName == "Delete")
    {     
        int index = Convert.ToInt32(e.CommandArgument);
        GridView1.DeleteRow(index);
        ((DataTable)ViewState["DataTable"]).Rows[index].Delete();
        ((DataTable)ViewState["DataTable"]).AcceptChanges();
        GridView1.DataSource = (DataTable)ViewState["Data"];
        GridView1.DataBind();
    }

回答by TalentTuner

try int.TryParse , this will solve the input string fromat problem , but why is it occuring that you need to check the CommandArgument you are setting.

尝试 int.TryParse ,这将解决输入字符串 fromat 问题,但为什么会出现需要检查您设置的 CommandArgument 的情况。

else if (e.CommandName == "DeletePart")
{
    int index =-1;
    if(int.TryParse(e.CommandArgument,out index)) //#1 line
        GridView1.DeleteRow(index);  //#2 line
}

回答by Praveen Nambiar

Seems like you didn't mention CommandArgumentproperty in the GridView.

好像你没有CommandArgumentGridView.

<asp:GridView runat="server" ID="gv" 
              CommandName="DeletePart" 
              CommandArgument='<%# Container.DataItemIndex %>'>         
</asp:GridView>

Add the CommandArgumentas shown above.

添加CommandArgument如上图所示。

回答by coder

Try this..

尝试这个..

In ASPX:

在 ASPX 中

<asp:GridView runat="server" ID="Gridview1" CommandName="delete" CommandArgument='<%#Container.DataItem.Index %>'/>

Cs:

CS

else if (e.CommandName == "DeletePart")
{
    int index = Convert.ToInt32(e.CommandArgument); 
    GridView1.DeleteRow(index);
}

回答by sophia

Thy This:) 

<asp:GridView ID="GridView1" runat="server"  CssClass="gridview"
                            HorizontalAlign="Left" PagerSettings-Visible="true" AllowPaging="True" 
                            PageSize ="5" Width="300px" >
                            <Columns>
                               <asp:CommandField ShowDeleteButton="True" ButtonType="Button" />      
                            </Columns>
                            </asp:GridView>

then code behinde:


    Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
        DirectCast(ViewState("CurrentDataReference"), DataTable).Rows.RemoveAt(e.RowIndex)
        GridView1.DataSource = DirectCast(ViewState("CurrentDataReference"), DataTable)
        GridView1.DataBind()

    End Sub