Client-Side Delete from Gridview(Hide-row and delete when page is saved)

Is there any way to hide a row dynamically in a gridview without a postback?  Each row in my grid has a delete button.  When the delete button is pressed I want it to appear to the user as if the corresponding row has been deleted.   The delete won't actually take place until there is a postback. 

I am using asp.net and javascript.  Here is a stripped down version of what I have. 

  

<script type="text/javascript" >
function getParentObjectId(fromId)
{
	var str;
	var indx;
	
	indx = fromId.lastIndexOf("_");
	str = fromId.substring(0, indx);
	return str;
}

function delcpt(rowitem)
{
   var rowid = getParentObjectId(rowitem.id);
    document.getElementById(rowid).style.display = 'none';
}
</script>

<asp:GridView ID="gvCPT" runat="server" DataKeyNames="Value" AutoGenerateColumns="False" Width="570px">
                                <Columns>                                    
                                    <asp:TemplateField>
                                    <ItemTemplate>
                                        <INPUT id="btnDelCPT" onclick="delcpt(this);" type="button" />   
                                    </ItemTemplate>
                                    </asp:TemplateField>
                                 </Columns>
</asp:GridView>
                                    
 
 I am getting a javascript error because 'rowid' is null.
0
Quin810
3/6/2008 2:31:01 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

2 Replies
939 Views

Similar Articles

[PageSpeed] 37

Hello,

 You can easily accomplish this using AJAX.NET and no javascript at all.

Below is an example which is self explanatory:


  

      <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
      
      <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
          <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
            DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display.">
            <Columns>
              <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
              <asp:BoundField DataField="VenueName" HeaderText="VenueName" SortExpression="VenueName" />
              <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
              <asp:TemplateField>
                <ItemTemplate>
                  <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
                </ItemTemplate>
              </asp:TemplateField>
            </Columns>
          </asp:GridView>
        </ContentTemplate>
      </asp:UpdatePanel>

 

Code Behind:

  

	protected void Button1_Click(object sender, EventArgs e)
	{
		Button btn = (Button) sender;
		GridViewRow row = (GridViewRow)btn.NamingContainer;
		
		GridView1.Rows[row.RowIndex].Visible = false;
	}

 

This will hide the row in which the button is clicked. To retrieve all of the rows you hide, you can add them to an array or collection in the button1_click event and retrieve it later. Or just loop though the gridview and find the rows you set the visibility to false. Like the following:

 

		foreach(GridViewRow row in GridView1.Rows)
		{
			if(row.Visible == false)
				Response.Write(row.Cells[1].Text);
		}

 

 

Hope this helps.
 


www.hopeasp.net
0
CSharpSean
3/7/2008 3:18:26 PM

Thanks for you answer.  I have actually found an even better way using javascript that won't even require an Ajax roundtrip to the server.

Here it is:

 

<script type="text/javascript" >

function getObjectInUC(fromId, targetId)
{
	var str;
	var indx;
	
	indx = fromId.lastIndexOf("_");
	str = fromId.substring(0, indx);
	str = str + "_" + targetId;
	return $(str);
}//getObjectInUC

function delrow(rowitem)
{
    
    var row = rowitem.parentNode.parentNode;
    row.style.visibility = "hidden";
    row.style.display = "none";   
    
     var target = getObjectInUC(rowitem.id, 'hdnVisible');           
        target.value = 0;   
       
}

</script>
 
 <asp:TemplateField ItemStyle-Width="30px">
    <ItemTemplate>
    <input id="btnDelCPT" runat="server" onclick="delrow(this);" type="button" />   
    <input type="hidden" id="hdnVisible" runat="server" value="1" />
    </ItemTemplate>
 </asp:TemplateField>
 //In the code behind when the save button is pressed I simply find out which rows contain hdnVisible.value = 0 and delete them.
    
  foreach (GridViewRow row in gvCPT.Rows)
            {
                HtmlInputHidden hdnVisible = row.FindControl("hdnVisible") as HtmlInputHidden;

                if (hdnVisible.Value == "0")
                {//code to delete
                }
                 if (hdnVisible.Value == "1")
                {//code to save
                }
            }
 
 

 

0
Quin810
3/7/2008 4:58:07 PM
Reply:

Similar Artilces:

How to delete controls in GridView when the delete button in a row is clicked
Hi,   I am having issues with my gridview.....i added 2 dropdown and 2 compare validators....whenever i delete a row though......the dropdown and compare validators are becoming null........thus when i click a button, it is still validating.............anyway to delete this when i click the delete button or even handle?   Please help.  ...

Delete (Hide) Row from Gridview without deleting from DataBase
I am populating some data in a GridView.I added a column with a checkbox.Now I want to generate a sort of print-preview...When Ich check some buttons and hit my printpriview button. I only want these (selected rows displayed).How can I do this?The checkbox thing is already working What I basically need is something to delete data temporaly from a GridView (not Database).I tryed GridViewRow.Dispose() which worked but then the paging was still implementet and the user sees still all pages =(I have tryed GridViewRow.Enabled = false which only turned the colors =(I have used GridViewRow.Visible ...

delete row or delete all in Gridview?
Hi there, I have a Gridview that bind the data from the .mdb  and I want to have 2 delete buttions, one is delete a row and the other one is delete all from the database.  How do I do it in code behind in c#?  thanks a lot row delete  (temp call rowDel) all delete (temp call allDel) with rowDel: i think you should bound one column in gridview  (or datagrid)<asp:ButtonColumn... and bout allDel: i think you should use a button distinct with gridview.Becoz your required is not complex , when allDel be push you don't care...

how can I delete a row from gridview in code-behind page without using sqldatasource control?
Hi, I have image button in my gridview. and I put its command name property 'delete'. could you please tell me what code should I have in my code behind page to delete row? I don't use sqldatasource for databound I use dataset. I use VB for coding. Thanks. Something like this: Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand If (e.CommandName.Equals("delete")) Then Dim btn As ImageButton = TryCast(e.CommandSource, ImageButton) If btn IsNot Nothing...

Adding data to gridview from two textboxes and then deleting them by delete button in each gridview row.
Hi, my app has 2 textboxes if i enter data and click add button they shud be added to gridview with 2 columns ex: custid from txtbox1 ... and custname frm txtbox2 added to gridview   with columns custid and custname then    foreach row a delete button shud appear in gridview and on clicking it shud delete the row can any one send me code for dis   thanks in advance Hi, In your Button Click Event write this code. DataControlField dCusId; DataControlField dCustName; dCusId.HeaderText = textbox1.text; dCustName.HeaderText = textbox2.text Gridv...

Gridview Delete not Deleting
I am trying to use a command button to delete a row from a gridview. When I click the command button though, the page posts but my record is still there... no errors, just nothing seems to happen. Below is what I think is the relevant code, let me know if you need to see anything else.  I'm kinda new to working with gridview objects, it would be nice if I could see what SQL command is acctually ran... maybe there are other things I can check too, I'm just not sure how.   <asp:GridView ID="GridView1" runat="server" AllowSorting="True"&nbs...

Delete a Row From A GridView Control
Well it is not just an ordinary delete. I have a Gridview which I populated manually. Then I need to delete a row which will be selected using a checkbox inside the gridview. I cant seem to find the way to just remove the specific row. I have already taken the rowIndex, but Gridview doesnt seem to allow me to delete a row unless I remove from a dataset or so. Anyhelp would be appreciated. Thanks - Mike use the property "DataKeyName" of the GridView. get the index and delete/remove the perticular row which you got through datakeyname property. and again bind your GridView. Thanx, [K...

How to delete row from GridView control
Hello,  I am working on an ASP.NET 2.0 app, and I am trying to wire up a "Delete" button to a gridview control on a form. Here is the code for the ASP :  <asp:GridView ID="gvInConditions" runat="server" AutoGenerateColumns="true" OnRowDeleting="gvInConditions_RowDeleting" DataKeyNames="Condition_ID" >         <Columns>                <asp:CommandField ButtonType="Button" SelectText=&...

deleting a gridview row > deleting a record by id?
I know this is supposed to be really simple but I'm stumped, despite all my reading: I've got a gridview full of 'Categories' pulled rom my SQL db; each row has a (hidden) 'category_id' column. My delete button should ensure that the appropriate record is marked for deletion by category_id. I understand that somehow the point of a datagrid is that it is bound to my datatable - but how do I leverage that so that deleting a grid row (which might be row index 1) finds and deletes the correct record (which might be category_id 3125)? (All I need to do is flag...

Error with Gridview when i delete the row that have only one row in gridview
 Dear all, i develop with asp.net 2005 and use gridview and set enable deleteing =true. I can delete record in gridview properly but when gridveiw has only one row and then i'm clike delete button , the error occurs :   Server Error in '/it' Application. Specified argument was out of the range of valid values.Parameter name: value Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentOutOfRangeExce...

how to implement client side delete confirmation before deleting any data
Hey Guys!  I am wondering how to implement the client side delete confirmation message box using javascript. I have to implement in such a way that when i select a delete linkbutton from datagrid, it should display a confirmation message box, 'Are you sure to delete?', If i clicked on OK button than delete that row else do nothing. Here is my code: aspx page: <asp:DataGrid Runat="server" ID="datagrid" ShowHeader="True" AutoGenerateColumns="False" PageSize="20" AllowPaging="True" OnDeleteCommand=&...

deleting saved-page xxx_filesdirectory deletes xxx.html file
I just noticed that (on Windows XP) when I delete an xxx_files directory (created by saving a complete web page), the corresponding xxx.html file also gets deleted. How is Seamonkey causing that to happen? (What Windows hooks is it using?) That behavior means that if a user decides they don't need the saved images and deletes the xxx_files directory, the user finds that the saved HTML is gone. Why the heck is Seamonkey doing that? Daniel /Daniel B./: > I just noticed that (on Windows XP) when I delete an xxx_files > directory (created by saving a ...

Help on deleting a row in Gridview control
Hi, I need to find out how to delete a row in the GridView control.  I have the following delete control in my GridView:<CODE><asp:TemplateField ItemStyle-HorizontalAlign=center ItemStyle-VerticalAlign="top"><ItemTemplate><asp:ImageButton ID=ibDelete runat=server ImageUrl="~/Images/delete.gif" CommandName="Delete"/></ItemTemplate> </asp:TemplateField></CODE> What events do I use and how do I get them to fire?  I just started using Gridviews.thanks. Hey,That should all you need to delete a row; a cli...

Deletes are not being deleted.
Using ASA 7.03 I am having a problem in deleting field service orders that have been completed. Just getting started with sync so I am probably making a dumb mistake or just leaving out a step. The download_delete_cursor script is: Select ordernumber from ServiceOrderEntryMaster where Tech = ? and Order_Complete = 'Y' This based on the verbose reply from the MobiLink Synchronization server is picking the correct work order ( number 326 ) and showing a Delete Row line in the log. But the work order is not being deleted on the remote side. What could I be doing wron...