user3009609
user3009609

Reputation:

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. 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

Upvotes: 0

Views: 19020

Answers (4)

Stuart
Stuart

Reputation: 143

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)
    }

Upvotes: 1

user3009609
user3009609

Reputation:

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. A simple solution that really shouldn't have taken me all day to complete!

Upvotes: 0

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17370

You need a way for your code to know which ID to delete. Here is how I would normally do it:

Replace your button with an ItemTemplate, and add the button in here instead:

    <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. 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).

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).

Then, to capture this you need to implement the RowCommand event of the GridView, and intercept the correct 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. This should do the trick.

Don't forget to bind the event to your GridView:

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

Upvotes: 2

Nathangrad
Nathangrad

Reputation: 1466

What you're looking for is indeed a simple solution.
You can use a foreach loop to search all DataRows within the DataTable for some kind of 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);
    }
}

Upvotes: 0

Related Questions