473,699 Members | 2,738 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
12 1850
I just cut and paste your code in my project, commented out the database
connection and retrieval lines ran it and realized where the error is. The
problem you have is one of case-sensitivity. You saved to the ViewState
using the following lines:

Viewstate("strS QLSelect") = strSQLSelect
ViewState("strS QLUpdate") = strSQLUpdate

and you retreived using the following lines:

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

Do you see the difference in the variable names between the ones you saved
and the ones you attempted to retrieve? The ViewState variable names are
case-sensitive.

--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"TB" wrote:
Hi again:

The result is:

EnableViewState = True

TB

Nov 19 '05 #11
TB
I have rewritten the whole thing, simplying somewhat and now using
session state instead of view state. It basically works. Thanks for
your help which has been a valuable lesson in bugtesting.

TB

Nov 19 '05 #12
You are welcome.
--
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"TB" wrote:
I have rewritten the whole thing, simplying somewhat and now using
session state instead of view state. It basically works. Thanks for
your help which has been a valuable lesson in bugtesting.

TB

Nov 19 '05 #13

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 information. However if I add another text box or dropdown box it does not seem to requery correctly. If...
3
3049
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 Arraylist. I've very little experience working with datagrids and arraylists so im finding this...
5
5660
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 local cache turned on all the time? Thanks for any suggestion.
3
2350
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 getting. Here's the relevant code. Thanks in advance! // As is, this code does not correctly call...
6
2547
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" http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/aspnet-commondatagridmistakes.asp they suggest disabling datagrid viewstate and adding...
2
5861
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 DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) { if...
4
2176
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 displayed in a list. This results in something like 200 names.
9
2720
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 (Page.IsPostBack) Then FillDataGrid()
8
3079
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 on my DataGrid but I'm not sure how to get Crystal Reports 10 to use as its datasource the dataset...
0
8612
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9171
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
6532
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5869
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4625
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3053
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
2
2342
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2008
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.