简体   繁体   English

Asp.Net C#单击按钮后从dataTable gridview删除行

[英]Asp.Net C# Delete row from dataTable gridview on button click

I'm displaying a datatable that selects a number of elements from the database (IncomingsId, Type, Cost, Frequency) and I'm not sure how to delete a row when a button is clicked. 我正在显示一个数据表,该数据表从数据库中选择了许多元素(IncomingsId,类型,成本,频率),并且不确定如何单击按钮时删除行。 I've tried many solutions so far but nothing is working. 到目前为止,我已经尝试了许多解决方案,但是没有任何效果。

Here is the button I have within my Grid view 这是我在“网格”视图中拥有的按钮

<asp:TemplateField HeaderText="Delete">  
         <ItemTemplate>  
            <asp:button id="DeleteRowButton" text="Delete Record" onclick="DeleteRowButton_Click" runat="server"/>
         </ItemTemplate>  
     </asp:TemplateField> 

And here is the code behind this page were I am creating the datatable. 这是我创建数据表时该页面后面的代码。

 SqlConnection con;

    public _Default()
    {
        con = new SqlConnection(@"MySQLConnection");
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DisplayRecord();
        }
    }

    public DataTable DisplayRecord()
    { 
        string userId = (HttpContext.Current.User.Identity.GetUserId());

            SqlDataAdapter Adp = new SqlDataAdapter("select * from Incomings where AspNetUsersId = '" + userId +"'", con);

        DataTable Dt = new DataTable();

        Dt.AcceptChanges();
        Adp.Fill(Dt);
            grid1.DataSource = Dt;
            grid1.DataBind();
     return Dt;
    }

    public void DeleteRowButton_Click(object sender, EventArgs e)
    {

    }

Cheers in advance for any help. 提前加油以寻求帮助。 I'm sure it's a simple resolution 我敢肯定这是一个简单的解决方案

You need a way for your code to know which ID to delete. 您需要一种让代码知道要删除哪个ID的方法。 Here is how I would normally do it: 这是我通常的做法:

Replace your button with an ItemTemplate , and add the button in here instead: 将按钮替换为ItemTemplate ,然后在此处添加按钮:

    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button Text="Delete" runat="server" CommandArgument='<%# Eval("userId") %>' CommandName="Delete" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

When you have the button this way, you now have access to a CommandArgument and CommandName attributes. 通过这种方式获得按钮后,现在可以访问CommandArgumentCommandName属性。 Notice the argument I am passing is Eval("userId") , the command name (as you will see later) is used to recognize what action you want to execute (this could be anything, is just a name). 注意,我传递的参数是Eval("userId") ,命令名称(如您将在后面看到的)用于识别要执行的操作(可以是任何名称,仅是名称)。

Replace the CommandArgument with whatever value(s) you want to pass to the server, using the name that came from the database/datasource (I am guessing it would be userId). 使用您想要传递给服务器的任何值替换CommandArgument ,并使用来自数据库/数据源的名称(我想它应该是userId)。

Then, to capture this you need to implement the RowCommand event of the GridView, and intercept the correct CommandName : 然后,要捕获此信息,您需要实现GridView的RowCommand事件,并拦截正确的CommandName

public void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        string userId = e.CommandArgument.ToString();
        //do something with the id
    }
}

Here you have to make sure the CommandName in your button, matches to whatever action you want to execute in the RowCommand . 在这里,您必须确保按钮中的CommandName与要在RowCommand执行的任何操作匹配。 This should do the trick. 这应该可以解决问题。

Don't forget to bind the event to your GridView: 不要忘记将事件绑定到您的GridView:

<asp:GridView OnRowCommand="GridView1_RowCommand" ID="GridView1" runat="server">
   ...
</asp:GridView>

just use this for the front-end code 将此用于前端代码

    <asp:GridView ID="grid1" OnRowDeleting="OnRowDeleting" DataKeyNames="deleteR" runat="server" AutoGenerateColumns="False"  CellPadding="4"  GridLines="None" style="width:100%"  >  

 <columns>  

    <asp:TemplateField HeaderText="Delete Row">
        <ItemTemplate>
            <asp:Button ID="btnDelete" runat="server" class="btn btn-primary" Text="Delete"  CommandName="Delete" OnRowDataBound="OnRowDataBound" />
        </ItemTemplate>
    </asp:TemplateField>

And have this in behind it: 并在其后面:

 protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int deleteR= Convert.ToInt32(grid1.DataKeys[e.RowIndex].Values[0]);
       //have a sql statement here that add's the parameter ID for the row you want to delete, something like
SqlCommand com  = new SqlCommand ("Delete FROM yourdatabase Where yourID = @yourID"
com.Parameters.AddWithValue("@yourID", yourID)
    }

What you're looking for is indeed a simple solution. 您要找的确实是一个简单的解决方案。
You can use a foreach loop to search all DataRow s within the DataTable for some kind of ID. 您可以使用foreach循环在DataTable所有DataRow搜索某种ID。
Here's an example of what I mean: 这是我的意思的示例:

String s = "/* IncomingsId for what you want to delete */";
foreach (DataRow r in dt.Rows) {
    if (r["IncomingsId"].ToString().Equals(s)) {
        dt.Rows.Remove(r);
    }
}

Just a quick update for anyone that's helped me, thanks for your advice. 只是对帮助我的任何人的快速更新,谢谢您的建议。 Asp.Net has it's own built in AutoGenerateDeleteButton and I set that to true and ran a bit of code behind it. Asp.Net具有自己内置的AutoGenerateDeleteButton,我将其设置为true并在其后面运行了一些代码。 A simple solution that really shouldn't have taken me all day to complete! 一个简单的解决方案真的不应该花我一整天才能完成!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM