473,569 Members | 2,844 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reusable datagrid, using viewstate items as for SQL statements / problems with life cycle

TB
Hi All:

I am trying to create a variation on the standard datagrid, whereby the
datagrid is only shown after pressing some buttons. This reason for
this is that I would like to use the same datagrid for several tables,
and the idea is that the button events store the the SQL select
statement and the SQL update statement in view state items, which can
the be reused for all the datagrid events (paging and editing).

However I seem to have a problem understanding the life cycle of the
page, which is why I would like to ask for some help here.

The error message I keep getting is:
"Object reference not set to an instance of an object.", always
referring to the line:
dgStaffOptions. DataSource = myDataSet.Table s("mytable"

(contained in a sub called showdatagrid() - 'dgStaffOptions ' is the ID
of the datagrid).

Below is the code, which I have simplied for clarity (only the first
button works). The asp:labels and the various reponse.write lines are
elements I have introduced during the bug testing.

HTML side contained in a user control (counter1u.ascx ):

<%@ Control Language="vb" AutoEventWireup ="false"
Codebehind="cou nter1u.ascx.vb" Inherits="qmsne t.counter1u"
TargetSchema="h ttp://schemas.microso ft.com/intellisense/ie5" %>
<h1>Staff Management - Standard options</h1>
<table>
<TBODY>
<tr>
<td vAlign="top">
<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="300"
border="0">
<TR>
<TD><p>Option s</p></TD>
<TD><p>Change </p></TD>
</TR>
<TR>
<TD><p>Position s</p></TD>
<TD align="center"> <asp:button id="Btn_Postion s" Text="Edit"
runat="server"> </asp:button></TD>
</TR>
<TR>
<TD><p>Compan y</p></TD>
<TD align="center"> <asp:button id="Btn_Company " Text="Edit"
runat="server"> </asp:button></TD>
</TR>
</TABLE>
<asp:label id="lbltest" Runat="server"> </asp:label><br>
<asp:label id="lbltest2" Runat="server"> </asp:label>
</td>
<td vAlign="top" width="600">
<asp:datagrid id="dgStaffOpti ons" runat="server" Runat="server"
OnUpdateCommand ="EditDataGrid_ Update"
OnCancelCommand ="EditDataGrid_ Cancel" OnEditCommand=" EditDataGrid_Ed it"
OnPageIndexChan ged="PageChange " AllowPaging="Tr ue" PageSize="4"
autogeneratecol umns="False" Width="400px">
<Columns>
<asp:BoundColum n DataField="ID" ReadOnly="True"
HeaderText="#"> </asp:BoundColumn >
<asp:BoundColum n DataField="Opti ons"
HeaderText="Opt ions"></asp:BoundColumn >
<asp:EditComman dColumn ItemStyle-CssClass="myLis tItem"
ButtonType="Lin kButton" UpdateText="Upd ate" HeaderText="Edi t"
CancelText="Can cel" EditText="Edit" ></asp:EditCommand Column>
</Columns>
</asp:datagrid>
</td>
</tr>
</TBODY>
</table>

Code-behind side (counter1u.ascx .vb):

Imports MySql.Data.MySq lClient
Imports qmsnet.test2
Public Class counter1u
Inherits System.Web.UI.U serControl

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnos tics.DebuggerSt epThrough()> Private Sub
InitializeCompo nent()

End Sub
Protected WithEvents lbltest As System.Web.UI.W ebControls.Labe l
Protected WithEvents Btn_Postions As
System.Web.UI.W ebControls.Butt on
Protected WithEvents Btn_Company As
System.Web.UI.W ebControls.Butt on
Protected WithEvents dgStaffOptions As
System.Web.UI.W ebControls.Data Grid
Protected WithEvents lbltest2 As System.Web.UI.W ebControls.Labe l

'NOTE: The following placeholder declaration is required by the Web
Form Designer.
'Do not delete or move it.
Private designerPlaceho lderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeCompo nent()
End Sub

#End Region

Dim myConnection As MySqlConnection
Dim myDataAdapter As MySqlDataAdapte r
Dim myDataSet As DataSet
Dim strSQLSelect As String
Dim strSQLUpdate As String
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
myConnection = New MySqlConnection ("server=mysql. mydomain.com;
user id=root; password=passwo rd; database=mybase ; pooling=false;" )
If Not Page.IsPostBack Then
strSQLSelect = "Select ID, Options from qmsPositions order
by Options"
strSQLUpdate = "Update"

Else
strSQLSelect = ViewState("StrS QLSelect")
strSQLUpdate = ViewState("StrS QLUpdate")

End If
'Response.Write ("load:" & strSQLSelect)
LoadDataFromDB( )

End Sub
Private Sub Page_Prerender( ByVal sender As System.Object, ByVal e
As System.EventArg s) Handles MyBase.PreRende r
Viewstate("strS QLSelect") = strSQLSelect
ViewState("strS QLUpdate") = strSQLUpdate
lbltest.Text = strSQLSelect
lbltest2.Text = strSQLUpdate

End Sub
Sub LoadDataFromDB( )
Order by Options"
myDataAdapter = New MySqlDataAdapte r(strSQLSelect,
myConnection)
myDataSet = New DataSet
Response.Write( "load3:" & strSQLSelect)
myDataAdapter.F ill(myDataSet, "mytable")
End Sub
Private Sub Btn_Postions_Cl ick(ByVal sender As System.Object, ByVal
e As System.EventArg s) Handles Btn_Postions.Cl ick
strSQLSelect = "Select ID, Options from qmsPositions Order by
Options"
strSQLUpdate = "Update qmsPositions set Options = 'columnvalue'
where ID = idvalue"
Showdatagrid()

End Sub
Private Sub Btn_Company_Cli ck(ByVal sender As System.Object, ByVal
e As System.EventArg s) Handles Btn_Company.Cli ck

End Sub
Sub PageChange(ByVa l sender As Object, ByVal e As
DataGridPageCha ngedEventArgs)
dgStaffOptions. CurrentPageInde x = e.NewPageIndex
Showdatagrid()

End Sub
Sub Showdatagrid()
dgStaffOptions. DataSource = myDataSet.Table s("mytable")
dgStaffOptions. DataBind()
End Sub
Sub EditDataGrid_Ed it(ByVal Sender As Object, ByVal E As
DataGridCommand EventArgs)
dgStaffOptions. EditItemIndex = E.Item.ItemInde x
Showdatagrid()
End Sub
Sub EditDataGrid_Ca ncel(ByVal Sender As Object, ByVal E As
DataGridCommand EventArgs)
dgStaffOptions. EditItemIndex = -1
Showdatagrid()
End Sub
Sub EditDataGrid_Up date(ByVal Sender As Object, ByVal E As
DataGridCommand EventArgs)
Dim IDint As String = E.Item.Cells(0) .Text
Dim Options As TextBox = E.Item.Cells(1) .Controls(0)
Dim SQLtemp As String
Dim objCommand As MySqlCommand
SQLtemp = Replace(strSQLU pdate, "columnvalu e", Options.Text)
SQLtemp = Replace(SQLtemp , "idvalue", IDint)
objCommand = New MySqlCommand(SQ Ltemp, myConnection)
Try
myConnection.Op en()
objCommand.Exec uteNonQuery()
myConnection.Cl ose()
Catch Ex As Exception
Response.Write( "<p><strong >An Error Occurred:</strong> " &
Ex.ToString() & "</p>" & vbCrLf)

Finally
myConnection.Cl ose()
End Try
LoadDataFromDB( )

dgStaffOptions. EditItemIndex = -1
Showdatagrid()
End Sub

End Class

=====

Thanks a bundle in advance!!

TB

Nov 19 '05 #1
12 1842
TB
I am not getting a lot of takers on this one, perhaps because I have
included so much code. But without it, I didn't feel I could explain my
case properly.

Any replies will higly appreciated.

Thanks in advance.

Trym

Nov 19 '05 #2
Hi Trym,

Welcome again. I looked briefly at your code. The error you get is
basically saying that myDataSet.Table s("mytable") was nothing at the time you
tried to bind it to the datagrid. It has nothing to do with the page
lifecycle.

If you have VS use the debugger to step through the code to see if
myDataSet.Table s("mytable") is nothing or simply add an if statement:

If not myDataSet is nothing andAlso not myDataSet.Table s("mytable") is
nothing Then
dgStaffOptions. DataSource = myDataSet.Table s("mytable")
dgStaffOptions. DataBind()
Else
Response.Write( "The DataSet at this stage is empty")
End If

If you get the message that the DataSet is empty, step again using the
Debugger to see if the method LoadDataFromDB is called before you reached to
that point again.

Let me know how far you get using the debugger.

--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"TB" wrote:
I am not getting a lot of takers on this one, perhaps because I have
included so much code. But without it, I didn't feel I could explain my
case properly.

Any replies will higly appreciated.

Thanks in advance.

Trym

Nov 19 '05 #3
TB
Thanks a lot for replying to my message.

I have inserted the code you had provided with one small change:
Iinstead of:
"If not myDataSet is nothing and Also not myDataSet.Table s("mytable")
is nothing Then"

I wrote:
"If Not myDataSet Is Nothing And Not myDataSet.Table s("mytable") Is
Nothing Then"

The result was that on the first run, i.e. without pressing the
btnPosition button and therefore without any postback, your inserted
condition was false and therefore the "The DataSet at this stage is
empty" message was printed.

Almost same thing happened after pressing the button and postback
therefore was true, the difference being that on the first run the line
"Response.Write ("load3:" & strSQLSelect)"
inside the LoadDataFromDB did return:
"load3:Sele ct ID, Options from qmsPositions order by Options"
but the second time (pressing the button and Page.IsPostBack = true)
that same code line returned only:
"load3:",
i.e StrSQLSelect = "". That lead me to discover through the debugger,
that that the Private Sub Page_Prerender does not run at all, not the
first time and not during postback. I am not not an ace programmer but
I should think that if the Private Sub Page_Prerender had fired, the
"Response.Write ("load3:" & strSQLSelect)" line should returned the same
result during postback because the StrSQLSelect variable would have
contained the value of the ViewState("StrS QLSelect") item.

Could this be the beginning of the path leading to the solution of the
problem at hand?

TB

Nov 19 '05 #4
TB
Oh, and yes: LoadDataFromDB( ) always loads.

TB

Nov 19 '05 #5
Somewhere there you are reseting the value of the variable StrSQLSelect
before you save it in the ViewState. Try place a break (during debugging) on
the first line within the Page_PreRender method and look at what values are
you saving in the ViewState for that variable. Then place a break on every
the end of every method to see when this variable (which private to the
class) turned into an empty string.
--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"TB" wrote:
Thanks a lot for replying to my message.

I have inserted the code you had provided with one small change:
Iinstead of:
"If not myDataSet is nothing and Also not myDataSet.Table s("mytable")
is nothing Then"

I wrote:
"If Not myDataSet Is Nothing And Not myDataSet.Table s("mytable") Is
Nothing Then"

The result was that on the first run, i.e. without pressing the
btnPosition button and therefore without any postback, your inserted
condition was false and therefore the "The DataSet at this stage is
empty" message was printed.

Almost same thing happened after pressing the button and postback
therefore was true, the difference being that on the first run the line
"Response.Write ("load3:" & strSQLSelect)"
inside the LoadDataFromDB did return:
"load3:Sele ct ID, Options from qmsPositions order by Options"
but the second time (pressing the button and Page.IsPostBack = true)
that same code line returned only:
"load3:",
i.e StrSQLSelect = "". That lead me to discover through the debugger,
that that the Private Sub Page_Prerender does not run at all, not the
first time and not during postback. I am not not an ace programmer but
I should think that if the Private Sub Page_Prerender had fired, the
"Response.Write ("load3:" & strSQLSelect)" line should returned the same
result during postback because the StrSQLSelect variable would have
contained the value of the ViewState("StrS QLSelect") item.

Could this be the beginning of the path leading to the solution of the
problem at hand?

TB

Nov 19 '05 #6
TB
Once again thanking you for the attention you are paying to this issue.

Experiement 1:

I have set a break point at
"Viewstate("str SQLSelect") = strSQLSelect" (first line of Private Sub
Page_PreRender)

And just as you predicted the program halted right there, which means
that Private Sub Page_PreRender is loaded.

Anyway, once the pogram had stopped at the above-mentioned line, I
opened Debug - Windows - Locals windows and I could see that both
Me.StrSQLSelect and Me.StrSQLUpdate contained the correct string values
("Select ID, Options from qmsPositions order by Options" and "Update
qmsPositions set Options = 'columnvalue' where ID = idvalue"). I could
also see that Me.viewstate.ke ys.count = 2 although next to
Me.viewstate.it em it said "<cannot view indexed property>".

Next experiment: Following your advice, I inserted breakpoints at every
"End Sub" statement.

Result for the first run (Page.IsPostBac k = False):

At all breaks StrSQLSelect = Select ID, Options from qmsPositions order
by Options" and StrSQLUpdate = "Update" - completely as intented, so no
problems so far.

Result for the second run (Pressing Btn_Postions and therefore
Page.IsPostBack = True):

Break 1 (at the beginning of Private Sub Page_Load): StrSQLSelect and
StrSQLUpdate are both nothing. 2 viewState items exist, but I cannot
see the values.

Break 2 (at the end of Private Sub Page_Load but just before jumping to
LoadDataFromDB) : StrSQLSelect and StrSQLUpdate are STILL nothing - THAT
IS NOT GOOD, because since Page.IsPostBack = true, the else part of the
if - End if statement has loaded where the two variables should be
filled witth corresponding viewstate values. If StrSQLSelect and
StrSQLUpdate remain nothing after that, then the viewstate item do not
contain the right data at postback. Why?? 2 viewState items still exist
but I cannot see the values.

Break 3 (at the end of LoadDataFromDB) : Same situation

Break 4 (at the of Private Sub Btn_Positions, but just before jumping
to Showdatagrid): Now StrSQLSelect and StrSQLUpdate now contain the
correct values: "Select ID, Options from qmsPositions Order by Options"
and "Update qmsPositions set Options = 'columnvalue' where ID =
idvalue" (marked in red in the locals window)

Break 5 (at the end of showdatagrid): Same situation

Break 6 (at the end of Private Sub Page_PreRender) : Same sitiation
except that the no values are marked in red in the locals window.

No datagrid is shown at the end of entire postback run.

Would you like me to send you the files and and SQL command file (so
that you can create the corresponding data source) so that you try it
yourself? (it might be faster - I don't want to waste too much of your
time) Perhaps I commit some stupid mistake handling VS that distort the
results.

TB

Nov 19 '05 #7
"TB" wrote:

...
Break 2 (at the end of Private Sub Page_Load but just before jumping to
LoadDataFromDB) : StrSQLSelect and StrSQLUpdate are STILL nothing - THAT
IS NOT GOOD, because since Page.IsPostBack = true, the else part of the
if - End if statement has loaded where the two variables should be
filled witth corresponding viewstate values. If StrSQLSelect and
StrSQLUpdate remain nothing after that, then the viewstate item do not
contain the right data at postback. Why?? 2 viewState items still exist
but I cannot see the values.
Add the following line at the beginning of the Page_Load:
Response.Write( "EnableViewStat e = " & Page.EnableView State)

If you get a message that "EnableViewStat e=False" then basically your
problem is that you have a setting somewhere that disabled the ViewState.
Look into both your web.config and the machine.config (which is located at
\Windows\Micros oft.Net\Framewo rk\xxx\config directory (where xxx is 1.0.3705
for version 1.0 of the Framework, or 1.1.4322 for version 1.1 or 2.0.50215
for version 2.x) Search for enableViewState . Usually you should find an
entry that looks like this:

<pages buffer="true" enableSessionSt ate="true" enableViewState ="true"
enableViewState Mac="true" autoEventWireup ="true" validateRequest ="true"/>

[...] Would you like me to send you the files and and SQL command file (so
that you can create the corresponding data source) so that you try it
yourself? (it might be faster - I don't want to waste too much of your
time) Perhaps I commit some stupid mistake handling VS that distort the
results.


I think you have done great using the debugger.

--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com

Nov 19 '05 #8
TB
Please hang on for another 24 hours. I will answer you tomorrow.

TB

Nov 19 '05 #9
TB
Hi again:

The result is:

EnableViewState = True

TB

Nov 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
464
by: Derek | last post by:
I have an aspx page where I use a reversebind and templates to edit the entire datagrid at one time. I added a textbox and button to change the parameter criteria and then rerun the databind2 procedure. That works fine the data is requeried and the new results are displayed in the datagrid and the reversebind works for saving the...
3
3037
by: Stephen | last post by:
I've got a datagrid with a remove button and I would like to add some code in the code behind page so as whenthe button is clicked the corresponding row in the datagrid is removed. The Datagrid is populated by the items in an arraylist shown in the code below. When the button is clicked I would also like the code to remove the items from the...
5
5639
by: Hardy Wang | last post by:
Hi all: I developed a web site, it passed various testing internally. When I put this site in production, I receive some error reports from this site saying "the viewstate is invalid for this page and might be corrupted". I am wandering what kind of client side problem may cause this error? Is it possible that user uses a browser which has...
3
2348
by: John | last post by:
The ItemCommand event not getting fired when I add both a BoundColumn and a ButtonColumn to a datagrid. When I add a ButtonColumn by itself, everything works fine, but as soon as I add a BoundColumn, the ItemCommand event doesn't seem to get called. I've been struggling with this for too long now, I'm certain there's something I'm not...
6
2545
by: sonic | last post by:
Hi, I am experimenting with different viewstate management ideas for large datagrids, and found a microsoft suggestion to turn it off, and only store relevant information by manually accessing viewstate. as per some helpful suggestins in MSDN "Common DataGrid Mistakes"...
2
5848
by: Steve Pierce | last post by:
I am having some issues with a runtime dropdownlist in a datagrid. The issue is that I cannot get ViewState to fill the selected index of a runtime dropdown properly on postback. I do not want to use template columns as they seem to be a little difficult to create at runtime. Any assistance would be very greatly appreciated. private void...
4
2174
by: John Wildes | last post by:
Hello I have a small program that I've created to generate accounting statements out of our policy managment system. The first part of the process is selecting the customer to create the statement for. In this process the application queries the database, returns a dataset of just customer names, and their customer code that is...
9
2711
by: rn5a | last post by:
A Form has a DataGrid which displays records from a SQL Server 2005 DB table. Users can modify the records using this DataGrid for which I am using EditCommandColumn in the DataGrid. This is the code: <script runat="server"> Dim sqlConn As New SqlConnection(".....") Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs) If Not...
8
3057
by: Brock | last post by:
I am trying to populate a Crystal Report from data in my DataGrid. The reason for this is that I want the user to be able to change values without updating the database, but still have their report reflect the values they anticipate committing to see hypothetical totals of columns from a set of records. These records are displaying properly...
0
7695
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7612
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7922
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6281
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5218
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3637
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2111
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.