PDA

View Full Version : Deleting a row on a GridView


stumac
07-03-2008, 12:49 AM
Hi Guys,

This is driving me nuts. I'm trying to delete a row from a gridview.
I have this code for the GridView;
<asp:GridView id="gv_auctions" EmptyDataText="You have no auction listings at present" OnRowEditing="gv_auctions_OnRowEditing" OnRowDeleting="gv_auctions_OnRowDeleting" datakeynames="auction_id" Width="760px" autogeneratecolumns="false" allowpaging="false" runat="server" BorderWidth="0px" BorderStyle="None">
<RowStyle BackColor="#ffffff" ForeColor="#444444" />
<AlternatingRowStyle BackColor="#eeeeee" ForeColor="#444444" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<div class="account_section_form_text" style="width:5%;">
No.
</div>
<div class="account_section_form_text" style="width:9%;">
Ref.
</div>
<div class="account_section_form_text" style="width:15%;">
Size
</div>
<div class="account_section_form_text" style="width:30%;">
Description
</div>
<div class="account_section_form_text" style="width:10%;">
Start Date
</div>
<div class="account_section_form_text" style="width:10%;">
End Date
</div>
<div class="account_section_form_text" style="width:8%;">
Reserve
</div>
<div class="account_section_form_text" style="width:8%;">
Buy Now
</div>
<div class="account_section_form_text" style="width:5%;">
&amp;nbsp;
</div>
</HeaderTemplate>
<ItemTemplate>
<div class="account_section_form_text" style="width:5%;">
<asp:Label runat="server" id="auction_id" text='<%# Eval("auction_id") %>'>
</asp:Label>
</div>
<div class="account_section_form_text" style="width:9%;">
<asp:Label runat="server" id="auction_refno" text='<%# Eval("auction_refno") %>'>
</asp:Label>
</div>
<div class="account_section_form_text" style="width:15%;">
<asp:Label runat="server" id="auction_adtype" text='<%# Eval("auction_ad_type") %>'>
</asp:Label>
</div>
<div class="account_section_form_text" style="width:30%;">
<asp:Label runat="server" id="auction_description" text='<%# Eval("auction_description") %>'>
</asp:Label>
</div>
<div class="account_section_form_text" style="width:10%;">
<asp:Label runat="server" id="auction_start" text='<%# Eval("startdate") %>'>
</asp:Label>
</div>
<div class="account_section_form_text" style="width:10%;">
<asp:Label runat="server" id="auction_end" text='<%# Eval("enddate") %>'>
</asp:Label>
</div>
<div class="account_section_form_text" style="width:8%;">
<asp:Label runat="server" id="auction_reserve" text='<%# Eval("auction_reserve") %>'>
</asp:Label>
</div>
<div class="account_section_form_text" style="width:8%;">
<asp:Label runat="server" id="auction_buynow" text='<%# Eval("auction_buynow") %>'>
</asp:Label>
</div>
<div class="account_section_form_text" style="width:5%;">
<asp:Button runat="server" Text="E" id="edit_auction_button" CommandName="Edit" CommandArgument='<%# Eval("auction_id") %>' cssClass="form_button_small" UseSubmitBehavior="false"></asp:Button>
<asp:Button runat="server" Text="X" id="delete_auction_button" CommandName="Delete" CommandArgument='<%# Eval("auction_id") %>' cssClass="form_button_small" UseSubmitBehavior="false"></asp:Button>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

OnRowDeleting Sub reads as follows;
Public Sub gv_auctions_OnRowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
Dim auction_id As Integer
auction_id = gv_auctions.DataKeys(e.RowIndex).Value
deleteAuction(auction_id)
End Sub

This works fine and dandy.

So I copied the code to another similar GridView I wanted which reads thus;
<asp:GridView id="gv_more_rates" datakeynames="rate_id" OnRowDeleting="gv_more_rates_onrowdeleting" Width="760px" ShowHeader="false" autogeneratecolumns="false" allowpaging="false" runat="server" BorderWidth="0px" BorderStyle="None">
<Columns>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<div class="account_section_form_text" style="text-transform:capitalize;">
<asp:Label runat="server" id="rates_name_label" text='<%# Eval("rates_name") %>'>
</asp:Label>
</div>
<div class="account_section_form_text" style="width:14%; text-align:center;">
<span>
<asp:Label runat="server" id="rates_colour_price_label" text='<%# Eval("rates_colour_price") %>' cssclass="form_text_more_contacts">
</asp:Label>
</span>
</div>
<div class="account_section_form_text" style="width:14%; text-align:center;">
<span>
<asp:Label runat="server" id="rates_mono_price_label" text='<%# Eval("rates_mono_price") %>' cssclass="form_text_more_contacts">
</asp:Label>
</span>
</div>
<div class="account_section_form_text" style="width:14%; text-align:center;">
<span>
<asp:Label runat="server" id="rates_type_area_label" text='<%# Eval("rates_type_area") %>' cssclass="form_text_more_contacts">
</asp:Label>
</span>
</div>
<div class="account_section_form_text" style="width:14%; text-align:center;">
<span>
&amp;nbsp;
<asp:Label runat="server" id="rates_trim_size_label" text='<%# Eval("rates_trim_size") %>' cssclass="form_text_more_contacts">
</asp:Label>
</span>
</div>
<div class="account_section_form_text" style="width:14%; text-align:center;">
<span>
&amp;nbsp;
<asp:Label runat="server" id="rates_bleed_area_label" text='<%# Eval("rates_bleed_area") %>' cssclass="form_text_more_contacts">
</asp:Label>
</span>
</div>
<div class="freeform_wrapper" style="width:6%; text-align:center;">
<asp:Button runat="server" CommandName=""Delete" CommandArgument='<%# Eval("rate_id") %>'Text="X" id="delete_more_rates_button" UseSubmitBehavior="false" cssClass="form_button_small"></asp:Button>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

OnRowDeleting sub reads as follows;
Public Sub gv_more_rates_onrowdeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
Dim rateid As Integer
rateid = gv_more_rates.DataKeys(e.RowIndex).Value
deleteRate(rateid)
End Sub

The 2nd GridView won't fire the delete event. Why, why, why, why, why???
I've been on this 5 hours now, searching and changing stuff but to no avail. I've debugged in VS2005 and the click goes straight to page.postback coding. If I include the <asp:commandfield with showdeletebutton then this fires the ondeleting event.

But I thought having the CommandName of "Delete" did this anyway? Of course it does, because on the first Gridview (i a seperate aspx file), it does exactly this.

What the hell else can be on the page which stops the ondeleting event firing. It doesn't databind the GridView until the last line of the deleteRate Sub (code excluded as it merely deletes the rateid entry from the table - not getting this far so problem not here). I mention this because I read that databinding at the wrong time can upset the event flow sometimes.

Anybody more worthy than I who can understand why one GridView works and the copied one doesn't?

Regards,

Stuart

wisemx
07-03-2008, 07:50 AM
Are you using the same datasource and bind method?


Which IDE by the way, VS2008? Express?
Salute,
Mark

wisemx
07-04-2008, 12:25 AM
Wow...You've got a lot of fighting going on in that.
Have you tried removing EnableEventValidation="false" and AutoEventWireup="false" ?
How about doing it without the update panel?
I'd guess something it going on there.

stumac
07-04-2008, 05:24 AM
Wisemx to the rescue again!! You're like a digital knight in shining armour man!!http://community.discountasp.net/emoticons/smilewinkgrin.gif

As crazy as it sounds, I've been around the coding block a bit so I like to hand code. When you've written a GridView a dozen times then the syntax becomes 2nd nature. Of course I having MSDN reference open at all times cos you can't remember everything! I've chased too many oddities over the years caused by VS Studio building solutions incorrectly that this problem outweighed the speed of development.............anyway these days I'm quicker at developing on a test server, with plenty of backups along the way!
A brief history, not to bore you, just to negate any VS build stupidity!
I do however download my code from the server to my local VS file to debug whenever anything stupid starts to happen so I can move through the code line by line (VS2005 Professional Edition)

So, hand coding using code behind. ASPX page for markup, ASPX.VB for the code. I also have a data access layer achieved through a db_access class (shown below as thisdata.getData).

In this case, the working Gridview databind is as follows;
Public Sub bindAuctions()
Dim thisdata As New db_data
Dim objReader As SqlDataAdapter
sqlparams.Clear()
sqlvalues.Clear()
sqlcomm = "getAuctions"
sqltype = "s"
sqlparams.Add("@mag_id")
sqlvalues.Add(Session("magid"))
Dim gva As GridView
gva = Page.Master.FindControl("MainContent").FindControl("gv_auctions")
gva.DataSource = thisdata.getData(sqlcomm, sqlparams, sqlvalues, "c").DefaultView
gva.DataBind()
la_rs_button.ForeColor = ColorTranslator.FromHtml("#00528f")
la_rs_button.BackColor = ColorTranslator.FromHtml("#ffffff")
End Sub

The "Bad" Gridview databind is as follows;
Public Sub bindMoreRates()
Dim thisdata As New db_data
Dim objReader As SqlDataAdapter
sqlparams.Clear()
sqlvalues.Clear()
sqlcomm = "getPubRate"
sqltype = "s"
sqlparams.Add("@mag_id")
sqlvalues.Add(Session("magid"))
Dim gv_mr As GridView
gv_mr = Page.Master.FindControl("MainContent").FindControl("gv_more_rates")
gv_mr.DataSource = thisdata.getData(sqlcomm, sqlparams, sqlvalues, "c").DefaultView
gv_mr.DataBind()
End Sub

As you can see, I just copied the code and changed the naming(intention is to have a single databind sub eventually for more streamlined code).

The latter (rates) is never reached after deletion as the onrowdeleting is just never fired. Yet almost identical code DOES fire in the auctions section. So why does the onrowdeleting not fire. Give or take names; the itemtemplate is the same; the button that fires it is the same; the GridView is the same. However, they are on 2 different pages.......the ONLY difference. But both use the same master page and code behind model.

Weird.

Hope this info helps you and the other gurus out there!

Cheers,

Stuart

wisemx
07-04-2008, 07:54 AM
I hear ya bro, it can be crazy. http://community.discountasp.net/emoticons/tongue.gif
As you probably see I do my best, get it right some of the time too.

I don't have to tell you the gridview is usually pretty easy to bind and use.
You may even want to throw something at me for that. http://community.discountasp.net/emoticons/wink.gif

At any rate, something odd is happening so let's try something odd.

In the page that is failing to perform place this below your top page directive:
<%@ MasterType VirtualPath="~/MasterPage.master" %>

Make that the second line on that page, just edit the called Master page.
Notice ~ it's called from the root in that example.
Salute,
Mark

stumac
07-04-2008, 09:03 AM
Hi Mark,


Tried that one. No difference.


I'm beginning to think it's my massive page size. Started using multiviews to capture different data using inline editing. Coupled this with updatepanel to make it a very sexy and streamlined data capture/editing process.


BUT.


aspx file has now reached 334kb, largest file I've ever worked with. I do compress the ViewState by overriding SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium events so I don't think it's that. The gridview that works is in another much smaller file so I think the framework is getting its knickers in a twist due to the bloat that it adds. End plan is to split out the functionality into smaller files so now may be the time.


I'm going to take out the gridview into another dedicated test file and see what happens.


Will let you know but if you think of anything else.....................


Cheers,


Stuart

stumac
07-04-2008, 09:37 AM
You is the man wisemx http://community.discountasp.net/emoticons/scool.gif ................although I've no reason why an updatepanel should stop the Delete command to fire.


PLUS...........the gridview that works (auctions one) is copied code and has that updatepanel, even down to its name, included in the file. And that works perfectly. Go figure..........


I've started to realise this week just how hit and miss the .NET framework is. I've wasted a lot of man hours going over simple code, simple working code, which stops working for bizarre and unexplained reasons...........rant,rant,rant.


Anyway, thanks Mark for helping me consider things I didn't even consider as being an issue


Now if I can only work out why it happens in one file but not another.........................


Cheers,


Stuart

stumac
07-04-2008, 10:15 AM
Update.


Now set up a new file, xtest.aspx. Removed all master pages and "other stuff". Content is now;


<%@ Page Language="vb" EnableEventValidation="false" AutoEventWireup="false" CodeFile="xtest.aspx.vb" Inherits="xtest" %>
<html>
<head>
<link href="engagei.css" rel="stylesheet" type="text/css" />
</head>
[b]
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
<Services>
<asp:ServiceReference Path="engagei_webservice.asmx" />
</Services>
<Scripts>
</Scripts>
</asp:ScriptManager>
<div id="progress_factsfigurescontent_container">
<asp:UpdateProgress id="progress_factsfigurescontent" runat="server" AssociatedUpdatePanelID="update_views">
<ProgressTemplate>
<div class="progress">
<img src="images/ajax-loader.gif" />
Retrieving Data...
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
<div>
<asp:Label runat="server" id="temp"></asp:Label>
</div>
<asp:UpdatePanel runat="server" id="update_views" updatemode="conditional">
<ContentTemplate>
<div class="account_info_wrapper_notop" style="padding-top:8px;">
<div class="account_info_wrapper_notop">
<asp:GridView id="gv_more_rates" datakeynames="rate_id" OnRowDeleting="gv_more_rates_onrowdeleting" Width="760px" ShowHeader="false" autogeneratecolumns="false" allowpaging="false" runat="server" BorderWidth="0px" BorderStyle="None">
<Columns>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<div class="account_section_form_text" style="text-transform:capitalize;">
<asp:Label runat="server" id="rates_name_label" text='<%# Eval("rates_name") %>'>
</asp:Label>
</div>
<div class="account_section_form_text" style="width:14%; text-align:center;">
<span>
<asp:Label runat="server" id="rates_colour_price_label" text='<%# Eval("rates_colour_price") %>' cssclass="form_text_more_contacts">
</asp:Label>
</span>
</div>
<div class="account_section_form_text" style="width:14%; text-align:center;">
<span>
<asp:Label runat="server" id="rates_mono_price_label" text='<%# Eval("rates_mono_price") %>' cssclass="form_text_more_contacts">
</asp:Label>
</span>
</div>
<div class="account_section_form_text" style="width:14%; text-align:center;">
<span>
<asp:Label runat="server" id="rates_type_area_label" text='<%# Eval("rates_type_area") %>' cssclass="form_text_more_contacts">
</asp:Label>
</span>
</div>
<div class="account_section_form_text" style="width:14%; text-align:center;">
<span>
&amp;nbsp;
<asp:Label runat="server" id="rates_trim_size_label" text='<%# Eval("rates_trim_size") %>' cssclass="form_text_more_contacts">
</asp:Label>
</span>
</div>
<div class="account_section_form_text" style="width:14%; text-align:center;">
<span>
&amp;nbsp;
<asp:Label runat="server" id="rates_bleed_area_label" text='<%# Eval("rates_bleed_area") %>' cssclass="form_text_more_contacts">
</asp:Label>
</span>
</div>
<div class="freeform_wrapper" style="width:6%; text-align:center;">
<asp:Button runat="server" CommandName=""Delete" CommandArgument='<%# Eval("rate_id") %>' Text="X" id="delete_more_rates_button" cssClass="form_button_small"></asp:Button>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>


Code behind page (xtest.aspx.vb) reads;


Imports System.Data.SqlClient
Imports System.Data
Imports System
Imports System.IO
Imports System.IO.Compression
Imports System.Drawing


Partial Class xtest
Inherits System.Web.UI.Page


Dim sqlcomm, sqltype As String
Dim sqlparams As New ArrayList
Dim sqlvalues As New ArrayList
Dim obj_return_string As String


Dim num_users,num_auctions As Integer


Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
temp.Text = "Not Postback"
Else
temp.Text = "Postback"
End If


Session("magid") = 44


bindMoreRates()
End Sub


Public Sub deleteRate(rateid)
sqlparams.Clear()
sqlvalues.Clear()


sqltype = "d"
sqlcomm = "deletePubRate"


sqlparams.Add("@rate_id")


sqlvalues.Add(rateid)


obj_return_string = ""
Dim db_access As New db_access
obj_return_string = db_access.getAccess(sqlcomm, sqltype, sqlparams, sqlvalues)


'FactsFiguresContent.ActiveViewIndex = 3


bindMoreRates()
End Sub


Public Sub bindMoreRates()
Dim thisdata As New db_data
Dim objReader As SqlDataAdapter


sqlparams.Clear()
sqlvalues.Clear()


sqlcomm = "getPubRate"
sqltype = "s"


sqlparams.Add("@mag_id")


sqlvalues.Add(Session("magid"))


Dim gv_mr As GridView
gv_mr = Page.FindControl("gv_more_rates")


gv_mr.DataSource = thisdata.getData(sqlcomm, sqlparams, sqlvalues, "c").DefaultView
gv_mr.DataBind()
End Sub


Public Sub gv_more_rates_onrowdeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
Dim rateid As Integer
rateid = gv_more_rates.DataKeys(e.RowIndex).Value
deleteRate(rateid)
End Sub


Protected Overloads Overrides Sub SavePageStateToPersistenceMedium(ByVal state As Object)
Dim formatter As New LosFormatter()
Dim writer As New StringWriter()
formatter.Serialize(writer, state)
Dim viewState As String = writer.ToString()
Dim data As Byte() = Convert.FromBase64String(viewState)
Dim compressedData As Byte() = ViewStateHelper.Compress(data)
Dim str As String = Convert.ToBase64String(compressedData)
ClientScript.RegisterHiddenField("__MYVIEWSTATE", str)
End Sub


Protected Overloads Overrides Function LoadPageStateFromPersistenceMedium() As Object
Dim viewstate As String = Request.Form("__MYVIEWSTATE")
Dim data As Byte() = Convert.FromBase64String(viewstate)
Dim uncompressedData As Byte() = ViewStateHelper.Decompress(data)
Dim str As String = Convert.ToBase64String(uncompressedData)
Dim formatter As New LosFormatter()
Return formatter.Deserialize(str)
End Function
End Class


The label called temp added as a reference marker.


Click on the X button, command name equal to delete, updateprogress displays but row doesn't delete.


I've given in already and used the commandfield...........why fight the system.


Why it works in my other GridView but not here is a mystery and will no doubt forever remain that way.


But I've got the desired result. But if you add CommandName="Delete" to a button in a GridView, shouldn't that fire the onrowdeleting event? I'm going to become a monk and chant alot......................................


Thanks for your time on this.


Cheers


Stuart