Showing posts with label instance. Show all posts
Showing posts with label instance. Show all posts

Saturday, March 31, 2012

System.FormatException: Input string was not in a correct format

I am getting above error

// Validate input
if ((userId.Trim() == string.Empty) || (password.Trim() == string.Empty))
return null;

// Get an instance of the account DAC using the DACFactory
IUserAccount dac = CData.DACFactory.FDACUserAccount.Create();

//On this line i am getting error.userId and Password are strings
UserAccountInfo userAccount = dac.Login(userId , password);
return userAccount;

Please sort out my problemI have made three assemblies. 1 is calling 2nd and 2nd is calling 3rd.
now when i call methods of 3rd from 1st through 2nd one i get "System.FormatException: Input string was not in a correct format" on every string manipulation. Even if it is throwing exceptions in string formats it gives that exception
When you use the Trim method, it expects the variable to be a string. When your variable is null, the Trim method would throw that FormatException. So you should rewrite your code to test your variable again null instead.
Ex:
<code>
if( userID == null )
{
//do something here
}

Thursday, March 22, 2012

system.nullreferenceexception problem

can anybody solve or tell more about this problem

System.NullReferenceException: Object reference not set to an instance of an object

[NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.ApplicationBlocks.UIProcess.WebFormViewManager.GetViewNameForCurrentRequest(IView currentView) +99
Microsoft.ApplicationBlocks.UIProcess.Navigator.GetControllerForView(IView view) +89
Microsoft.ApplicationBlocks.UIProcess.WebFormView.WebFormView_Load(Object sender, EventArgs e) +312
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.OnLoad(EventArgs e) +67
System.Web.UI.Control.LoadRecursive() +35
System.Web.UI.Page.ProcessRequestMain() +733

Version Information: Microsoft .NET Framework Version:1.1.4322.2300; ASP.NET Version:1.1.4322.2300

thanks

this is not enough info to tell you exactly what you are doing wrong, but - you are calling on a variable that you did not assign a value to. It could be something as simple as:

int a; // giving it no value

int b = a; // as you can see, you didnt *** value into a, so you are calling on a null value


this is not enough info to tell you exactly what you are doing wrong, but - you are calling on a variable that you did not assign a value to. It could be something as simple as:

int a; // giving it no value

int b = a; // as you can see, you didnt put a value into a, so you are calling on a null value


Please provide the code so we can look into the problem!

Thanks for replies.

actually i m totally new to asp.net. i have to modify an already existing project. so its more confusing bcoz i dont know very much about the actual code. the strange thing i notice that website run properly for some time at starting. and after some time it will show nothing except the system.nullreference exception on each page. does this information help to u understand the problem??

is it related to something like cache expired? i dont know abt this problem and that's why i m searching net for a solution.

thanks

System.NullReferenceException: Object reference not set to an inst

I'm loading an Array below but getting the error "Object reference not set t
o
an instance saying 'ItemNumber = CType(Args.Item.FindControl("ItemNumber"),
TextBox).Text' is the error line.
I DON'T KNOW WHAT I'M DOING WRONG I USED ASP.NETWebMatrix and its working
well!!
Any help!!
I have declared ItemNumber as u can see below
" :-
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
' Load array ItemNumberList with item numbers
'Dim ItemNumberList = New ArrayList
Dim ItemNumberList = New ArrayList
DBConnection = New
SqlConnection(" server=(local);database=Northwind;integr
ated security=true;")
DBConnection.Open()
SQLString = "SELECT ItemNumber FROM products1 ORDER BY ItemNumber"
DBCommand = New SqlCommand(SQLString, DBConnection)
DBReader = DBCommand.ExecuteReader()
While DBReader.Read()
ItemNumberList.Add(DBReader("ItemNumber"))
End While
DBReader.Close()
DBConnection.Close()
ItemNumberList.TrimToSize()
End Sub
Dim ItemNumber As String
ItemNumber = CType(Args.Item.FindControl("ItemNumber"), TextBox).TextHi,
The code in Page_Load() has nothing to do with these two lines:
Dim ItemNumber As String
ItemNumber = CType(Args.Item.FindControl("ItemNumber"), TextBox).Text
What is Args? It looks like you already know the control name. Why not?:
ItemNumber = ItemNumber.Text
That should work fine. Are the two lines of code above in another
subroutine? The code you posted doesn't seem relevant in any way to each
other. Please post a better sample of what you are trying to do. Thanks
and Good luck! Ken.
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.
"Patrick.O.Ige" <PatrickOIge@.discussions.microsoft.com> wrote in message
news:F81983BF-9835-4BDA-9205-18985CF18FED@.microsoft.com...
> I'm loading an Array below but getting the error "Object reference not set
to
> an instance saying 'ItemNumber =
CType(Args.Item.FindControl("ItemNumber"),
> TextBox).Text' is the error line.
> I DON'T KNOW WHAT I'M DOING WRONG I USED ASP.NETWebMatrix and its working
> well!!
> Any help!!
>
> I have declared ItemNumber as u can see below
> " :-
> Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles MyBase.Load
> ' Load array ItemNumberList with item numbers
> 'Dim ItemNumberList = New ArrayList
> Dim ItemNumberList = New ArrayList
> DBConnection = New
> SqlConnection(" server=(local);database=Northwind;integr
ated
security=true;")
> DBConnection.Open()
> SQLString = "SELECT ItemNumber FROM products1 ORDER BY ItemNumber"
> DBCommand = New SqlCommand(SQLString, DBConnection)
> DBReader = DBCommand.ExecuteReader()
> While DBReader.Read()
> ItemNumberList.Add(DBReader("ItemNumber"))
> End While
> DBReader.Close()
> DBConnection.Close()
> ItemNumberList.TrimToSize()
> End Sub
> Dim ItemNumber As String
> ItemNumber = CType(Args.Item.FindControl("ItemNumber"), TextBox).Text
>

System.NullReferenceException: Object reference not set to an inst

I'm loading an Array below but getting the error "Object reference not set to
an instance saying 'ItemNumber = CType(Args.Item.FindControl("ItemNumber"),
TextBox).Text' is the error line.
I DON'T KNOW WHAT I'M DOING WRONG I USED ASP.NETWebMatrix and its working
well!!
Any help!!

I have declared ItemNumber as u can see below
" :-

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
' Load array ItemNumberList with item numbers
'Dim ItemNumberList = New ArrayList
Dim ItemNumberList = New ArrayList
DBConnection = New
SqlConnection("server=(local);database=Northwind;integrated security=true;")
DBConnection.Open()
SQLString = "SELECT ItemNumber FROM products1 ORDER BY ItemNumber"
DBCommand = New SqlCommand(SQLString, DBConnection)
DBReader = DBCommand.ExecuteReader()
While DBReader.Read()
ItemNumberList.Add(DBReader("ItemNumber"))
End While
DBReader.Close()
DBConnection.Close()
ItemNumberList.TrimToSize()
End Sub

Dim ItemNumber As String
ItemNumber = CType(Args.Item.FindControl("ItemNumber"), TextBox).TextHi,

The code in Page_Load() has nothing to do with these two lines:

Dim ItemNumber As String
ItemNumber = CType(Args.Item.FindControl("ItemNumber"), TextBox).Text

What is Args? It looks like you already know the control name. Why not?:

ItemNumber = ItemNumber.Text

That should work fine. Are the two lines of code above in another
subroutine? The code you posted doesn't seem relevant in any way to each
other. Please post a better sample of what you are trying to do. Thanks
and Good luck! Ken.

--
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.

"Patrick.O.Ige" <PatrickOIge@.discussions.microsoft.com> wrote in message
news:F81983BF-9835-4BDA-9205-18985CF18FED@.microsoft.com...
> I'm loading an Array below but getting the error "Object reference not set
to
> an instance saying 'ItemNumber =
CType(Args.Item.FindControl("ItemNumber"),
> TextBox).Text' is the error line.
> I DON'T KNOW WHAT I'M DOING WRONG I USED ASP.NETWebMatrix and its working
> well!!
> Any help!!
>
> I have declared ItemNumber as u can see below
> " :-
> Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles MyBase.Load
> ' Load array ItemNumberList with item numbers
> 'Dim ItemNumberList = New ArrayList
> Dim ItemNumberList = New ArrayList
> DBConnection = New
> SqlConnection("server=(local);database=Northwind;integrated
security=true;")
> DBConnection.Open()
> SQLString = "SELECT ItemNumber FROM products1 ORDER BY ItemNumber"
> DBCommand = New SqlCommand(SQLString, DBConnection)
> DBReader = DBCommand.ExecuteReader()
> While DBReader.Read()
> ItemNumberList.Add(DBReader("ItemNumber"))
> End While
> DBReader.Close()
> DBConnection.Close()
> ItemNumberList.TrimToSize()
> End Sub
> Dim ItemNumber As String
> ItemNumber = CType(Args.Item.FindControl("ItemNumber"), TextBox).Text
Hi Ken and thanks for the reply! (My Code below!!!)
What i'm trying to do is a datagrid that has Add,Update,Delete commands.My
Add command is working but my Delete and Update command is giving error :-
System.NullReferenceException: Object reference not set to an instance of an
object.
Refering to the line code:- ItemNumber =
CType(Args.Item.FindControl("ItemNumber"), TextBox).Text
Don't know whats wrong IT WORKS WITH ASP.NETWEBMATRIX!!
But VS.Net give such errors!
Any help Thanks!!

'Option Explicit On
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls

Public Class datagrid_edit_delete
Inherits System.Web.UI.Page

'Dim ItemTypes As New ArrayList
Protected ItemTypes As New ArrayList
'Protected WithEvents ItemType As System.Web.UI.WebControls.DropDownList
Protected WithEvents Button As System.Web.UI.WebControls.Button
Protected WithEvents PageButtons As System.Web.UI.WebControls.PlaceHolder
Protected WithEvents UpdateMessage As System.Web.UI.WebControls.Label
Protected WithEvents DataGridDisplay As System.Web.UI.WebControls.DataGrid
Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox
'Dim ItemNumberList As New ArrayList

'Protected WithEvents ItemTypes As System.Web.UI.WebControls.DropDownList

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent()

End Sub

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

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

#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here

Dim DBConnection As SqlConnection
Dim DBCommand As SqlCommand
Dim DBReader As SqlDataReader
Dim SQLString As String
Dim PageSize As Integer = 6

'-- Load array ItemNumberList with item numbers
'Dim ItemNumberList = New ArrayList
Dim ItemNumberList = New ArrayList
DBConnection = New
SqlConnection("server=(local);database=Northwind;integrated security=true;")
DBConnection.Open()
SQLString = "SELECT ItemNumber FROM products1 ORDER BY ItemNumber"
DBCommand = New SqlCommand(SQLString, DBConnection)
DBReader = DBCommand.ExecuteReader()
While DBReader.Read()
ItemNumberList.Add(DBReader("ItemNumber"))
End While
DBReader.Close()
DBConnection.Close()
ItemNumberList.TrimToSize()

'-- Create Paging Buttons
Dim StartIndex = 0
Dim EndIndex As Integer
Dim StartKey As String
Dim EndKey As String
Dim i As Integer

PageButtons.Controls.Clear()
For i = 1 To Math.Ceiling(ItemNumberList.Count / PageSize)

EndIndex = StartIndex + PageSize - 1
If EndIndex > ItemNumberList.Count - 1 Then
EndIndex = ItemNumberList.Count - 1
End If

StartKey = ItemNumberList(StartIndex)
EndKey = ItemNumberList(EndIndex)

Dim PageButton As Button
PageButton = New Button
PageButton.Text = i
PageButton.ID = "P" & i
PageButton.CommandName = StartKey & "|" & EndKey
PageButton.Style("width") = "20px"
PageButton.Style("background-color") = "#F0F0F0"
AddHandler PageButton.Command, AddressOf GetPage
PageButtons.Controls.Add(PageButton)

StartIndex += PageSize

Next

'== CREATE ARRAYLIST FOR BINDING ITEM TYPES

ItemTypes = New ArrayList
DBConnection = New
SqlConnection("server=(local);database=Northwind;integrated security=true;")
DBConnection.Open()
SQLString = "SELECT DISTINCT ItemType FROM products1 ORDER BY
ItemType"
DBCommand = New SqlCommand(SQLString, DBConnection)
DBReader = DBCommand.ExecuteReader()
While DBReader.Read()
ItemTypes.Add(DBReader("ItemType"))
End While
DBReader.Close()
DBConnection.Close()

If Not Page.IsPostBack Or ViewState("Updated") = True Then

DBConnection = New
SqlConnection("server=(local);database=Northwind;integrated security=true;")
DBConnection.Open()
SQLString = "SELECT TOP " & PageSize & " * FROM products1 ORDER
BY ItemNumber"
DBCommand = New SqlCommand(SQLString, DBConnection)
DBReader = DBCommand.ExecuteReader()
DataGridDisplay.DataSource = DBReader
DataGridDisplay.DataBind()
DBReader.Close()
DBConnection.Close()

Dim FirstButton As Button
FirstButton = CType(PageButtons.FindControl("P1"), Button)
FirstButton.Style("background-color") = "#990000"
FirstButton.Style("color") = "#FFFFFF"

ViewState("Updated") = False

End If

End Sub

Sub GetPage(ByVal Src As Object, ByVal Args As CommandEventArgs)

Dim DBConnection As SqlConnection
Dim DBCommand As SqlCommand
Dim DBReader As SqlDataReader
Dim SQLString As String

Dim Keys() As String
Keys = Split(Args.CommandName, "|")

DBConnection = New
SqlConnection("server=(local);database=Northwind;integrated security=true;")
DBConnection.Open()
SQLString = "SELECT * FROM products1 WHERE " & _
"ItemNumber >= '" & Keys(0) & "' AND " & _
"ItemNumber <= '" & Keys(1) & "' " & _
"ORDER BY ItemNumber"
DBCommand = New SqlCommand(SQLString, DBConnection)
DBReader = DBCommand.ExecuteReader()
DataGridDisplay.DataSource = DBReader
DataGridDisplay.DataBind()
DBReader.Close()
DBConnection.Close()

'-- Highlight clicked button
Dim Item As Button
Dim ThisButton As Button
For Each Item In PageButtons.Controls
ThisButton = CType(Item, Button)
ThisButton.Style("background-color") = "#F0F0F0"
ThisButton.Style("color") = "#000000"
Next
ThisButton = CType(PageButtons.FindControl(Src.id), Button)
ThisButton.Style("background-color") = "#990000"
ThisButton.Style("color") = "#FFFFFF"

End Sub
Function SetIndex(ByVal TheItem As String)
Dim i As Integer
For i = 0 To ItemTypes.Count - 1
If TheItem = ItemTypes(i) Then
Return i
End If
Next
End Function

Sub EditRecord(ByVal Src As Object, ByVal Args As
DataGridCommandEventArgs)

Dim Command As String
Dim ItemNumber As String
Dim ItemType As String
Dim ItemSupplier As String
Dim ItemName As String
Dim ItemDescription As String
Dim ItemPrice As String
Dim ItemQuantity As String
Dim DBConnection As SqlConnection
Dim DBCommand As SqlCommand
Dim DBReader As SqlDataReader
Dim SQLString As String

Command = Args.CommandSource.Text

ItemNumber = CType(Args.Item.FindControl("ItemNumber"), TextBox).Text
ItemType = CType(Args.Item.FindControl("ItemType"),
DropDownList).SelectedItem.Text
ItemSupplier = CType(Args.Item.FindControl("ItemSupplier"),
TextBox).Text
ItemName = CType(Args.Item.FindControl("ItemName"), TextBox).Text
ItemDescription = CType(Args.Item.FindControl("ItemDescription"),
TextBox).Text
ItemPrice = CType(Args.Item.FindControl("ItemPrice"), TextBox).Text
ItemQuantity = CType(Args.Item.FindControl("ItemQuantity"),
TextBox).Text

UpdateMessage.Text = " "

Dim ValidRecord As Boolean = True

If Command = "Add" Or Command = "Update" Then

'-- CHECK FOR VALID RECORD --

'-- Check for valid ItemNumber
If Len(ItemNumber) <> 6 Then
UpdateMessage.Text &= "- Invalid Item Number length "
ValidRecord = False
ElseIf Not IsNumeric(Right(ItemNumber, 4)) Then
UpdateMessage.Text &= "- Invalid Item Number format "
ValidRecord = False
Else
ItemNumber = UCase(ItemNumber)
End If

'-- Check for missing Item Supplier
If ItemSupplier = "" Then
UpdateMessage.Text &= "- Missing Supplier "
ValidRecord = False
End If

'-- Check for missing Item Name
If ItemName = "" Then
UpdateMessage.Text &= "- Missing Name "
ValidRecord = False
End If

'-- Check for missing Item Description
If ItemDescription = "" Then
UpdateMessage.Text &= "- Missing Description "
ValidRecord = False
End If

'-- Check for valid Item Price
If Not IsNumeric(ItemPrice) Then
UpdateMessage.Text &= "- Invalid Price format "
ValidRecord = False
End If

'-- Check for valid Item Quantity
If Not IsNumeric(ItemQuantity) Then
UpdateMessage.Text &= "- Invalid Quantity format "
ValidRecord = False
End If

If ValidRecord = True And Command = "Add" Then

'-- CHECK FOR DUPLICATE RECORD --
DBConnection = New
SqlConnection("server=(local);database=Northwind;integrated security=true;")
DBConnection.Open()
SQLString = "SELECT Count(*) FROM products1 WHERE ItemNumber
= '" & ItemNumber & "'"
DBCommand = New SqlCommand(SQLString, DBConnection)
If DBCommand.ExecuteScalar() <> 0 Then
UpdateMessage.Text = "- Duplicate Item Number. Record
not added."
ValidRecord = False
End If
DBConnection.Close()

End If

End If

If ValidRecord = True Then

Select Case Command

Case "Add"
SQLString = "INSERT INTO products1 " & _
"(ItemNumber, ItemType, ItemSupplier, ItemName, " & _
"ItemDescription, ItemPrice, ItemQuantity) VALUES(" & _
"'" & ItemNumber & "', " & _
"'" & ItemType & "', " & _
"'" & Replace(ItemSupplier, "'", "''") & "', " & _
"'" & Replace(ItemName, "'", "''") & "', " & _
"'" & Replace(ItemDescription, "'", "''") & "', " & _
ItemPrice & ", " & _
ItemQuantity & ")"
UpdateMessage.Text = "- Record " & ItemNumber & " added"

Case "Update"
SQLString = "UPDATE products1 SET " & _
"ItemType = '" & ItemType & "', " & _
"ItemSupplier = '" & Replace(ItemSupplier, "'", "''")
& "', " & _
"ItemName = '" & Replace(ItemName, "'", "''") & "', "
& _
"ItemDescription = '" & Replace(ItemDescription, "'",
"''") & "', " & _
"ItemPrice = " & ItemPrice & ", " & _
"ItemQuantity = " & ItemQuantity & " " & _
"WHERE ItemNumber = '" & ItemNumber & "'"
UpdateMessage.Text = "- Record " & ItemNumber & " updated"

Case "Delete"
SQLString = "DELETE FROM products1 WHERE ItemNumber = '"
& ItemNumber & "'"
UpdateMessage.Text = "- Record " & ItemNumber & " deleted"

End Select

DBConnection = New
SqlConnection("server=(local);database=Northwind;integrated security=true;")
DBConnection.Open()
DBCommand = New SqlCommand(SQLString, DBConnection)
DBCommand.ExecuteNonQuery()
DBConnection.Close()

If Command = "Add" Or Command = "Delete" Then

ViewState("Updated") = True
Page_Load(Me, EventArgs.Empty)
'Page_Load(ByRef sender As System.Object, ByRef e As
System.EventArgs)
End If

End If

End Sub

End Class
Hi,

The datagrid... The datagrid isn't my thing. I used it a couple times,
got frustrated, and wrote my own. Hopefully someone in the group can point
you in the right direction. I looked through the help file that comes with
VS.Net, in VS.Net they reference .controls(0) to CType() the control:

Sub MyDataGrid_Update(sender As Object, e As DataGridCommandEventArgs)
' For bound columns the edited value is stored in a Textbox.
' The TextBox is the 0th element in the column's cell.
Dim qtyText As TextBox = CType(e.Item.Cells(2).Controls(0), TextBox)
Dim priceText As TextBox = CType(e.Item.Cells(3).Controls(0),
TextBox)

Dim item As String = e.Item.Cells(1).Text
Dim qty As String = qtyText.Text
Dim price As String = priceText.Text

Here is the link to the full source:
"ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemWebUIWebControlsDataGridC
ommandEventArgsClassTopic.htm"

Open up the help and paste that in the address bar.

I would try that. I don't know why WebMatrix would work and VS.Net
wouldn't. Good luck! Ken.

--
Ken Dopierala Jr.
For great ASP.Net web hosting try:
http://www.webhost4life.com/default.asp?refid=Spinlight
If you sign up under me and need help, email me.

System.NullReferenceException: Object reference not set to an instance of an object.

Why do I get above error message while executing this code:

Public Sub DropDown_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Dim list As DropDownList = CType(sender, DropDownList)
Dim cell = CType(list.Parent, TableCell)
Dim item = CType(cell.Parent, DataGridItem)
Dim index = item.ItemIndex

Dim ds As DataSet
ds = DataGrid1.DataSource

Dim row As DataRow
row = ds.Tables(0).Select("ID = '" + item.Cells(0).Text + "'")(0)
'<-- ERROR
End SubSet a break point on the line

row = ds.Tables(0).Select("ID = '" + item.Cells(0).Text + "'")(0)

and see what is null there.

Could be:
no tables in ds;
no Cells(o) in item;
no item;
select doesn't return anything
...

Debug it.

Eliyahu

"John Smith" <john.smith@.microsoft.com> wrote in message
news:%Zahg.3487$oj5.1152205@.news.siol.net...
> Why do I get above error message while executing this code:
> Public Sub DropDown_SelectedIndexChanged(ByVal sender As System.Object,
> ByVal e As System.EventArgs)
> Dim list As DropDownList = CType(sender, DropDownList)
> Dim cell = CType(list.Parent, TableCell)
> Dim item = CType(cell.Parent, DataGridItem)
> Dim index = item.ItemIndex
> Dim ds As DataSet
> ds = DataGrid1.DataSource
> Dim row As DataRow
> row = ds.Tables(0).Select("ID = '" + item.Cells(0).Text + "'")(0)
> '<-- ERROR
> End Sub
Thank you.

"ds" was null. It seems I need to add DataSource into Session object
somehow. Beginner mistake. It seems DataGrid1.DataSource is not persistance?
> "ds" was null. It seems I need to add DataSource into Session object
> somehow. Beginner mistake. It seems DataGrid1.DataSource is not
> persistance?

I've declared ds as global Shared variable and it works fine so far.
Just note, that global Shared variables are shared between user sessions. It
means that if there will be multiple users using the app in the same time,
they will affect each other.

Eliyahu

"John Smith" <john.smith@.microsoft.com> wrote in message
news:tWbhg.3493$oj5.1152346@.news.siol.net...
>> "ds" was null. It seems I need to add DataSource into Session object
>> somehow. Beginner mistake. It seems DataGrid1.DataSource is not
>> persistance?
> I've declared ds as global Shared variable and it works fine so far.
> Just note, that global Shared variables are shared between user sessions.
> It
> means that if there will be multiple users using the app in the same time,
> they will affect each other.

So, should I declare it as "static" or as simple global variable (without
"shared")?
What is your data source?

"John Smith" <john.smith@.microsoft.com> wrote in message
news:Dpchg.3498$oj5.1152406@.news.siol.net...
>> Just note, that global Shared variables are shared between user sessions.
>> It
>> means that if there will be multiple users using the app in the same
>> time, they will affect each other.
> So, should I declare it as "static" or as simple global variable (without
> "shared")?
> What is your data source?

XML
If you can't re-populate the datasource on every postback, you can store it
in a session variable.

Eliyahu

"John Smith" <john.smith@.microsoft.com> wrote in message
news:G7ehg.3500$oj5.1153527@.news.siol.net...
>> What is your data source?
> XML
> If you can't re-populate the datasource on every postback, you can store
> it
> in a session variable.

There is no other way but session object?
John Smith wrote:
>> If you can't re-populate the datasource on every postback, you can
>> store it
>> in a session variable.
> There is no other way but session object?
If you need it to be session-specific, the session object makes it easy.
Sure, you can create a global hashtable keyed by some property of the
users of your application, but
1. this hashtable could get rather large, and
2. if you are not careful, bugs are hard to avoid.

Just out of curiosity, what is your objection to the session object?
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.
> Just out of curiosity, what is your objection to the session object?

I am beginner and I have never used it before. I'll try it now.
John Smith wrote:
>> Just out of curiosity, what is your objection to the session object?
> I am beginner and I have never used it before. I'll try it now.
Ah!
I typically use a pattern like this in my pages:

Private _CachedDS as dataset
Private Propery CachedDS() as dataset
Get
If _CachedDS Is Nothing Then
If Not Session("CachedDS") Is Nothing Then
_CachedDS = CType(Session("CachedDS"), dataset)
End If
End If
Return _CachedDS
End Get
Set(ByVal Value As dataset)
Session("CachedDS") = Value
_CachedDS = Value
End Set
End Property

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Not IsPostBack Then
BindDataGrid()
End If

End Sub

...
Sub BindDataGrid
Dim ds as dataset
if CachedDS Is Nothing then
FillDataSet()
End If
'bind the grid
Dim ds as dataset=CachedDS
With DataGrid1
.DataSource=ds
.DataMember = ...
.DataBind
End With

End Sub

Sub FillDataSet()
Try
CachedDS = DataLayer.RetrieveData(parms)
Catch ex
'handle error
End Try
End Sub

Public Sub DropDown_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Dim list As DropDownList = CType(sender, DropDownList)
Dim cell = CType(list.Parent, TableCell)
Dim item = CType(cell.Parent, DataGridItem)
Dim index = item.ItemIndex

Dim ds As DataSet
if not CachedDS is Nothing then
ds = CachedDS
Else
'throw an error? call FillDataset? up to you.
End If

Dim row As DataRow
row = ds.Tables(0).Select("ID = '" + item.Cells(0).Text +
"'")(0)
etc.

HTH,
Bob Barrows
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.
John Smith wrote:
>> Just note, that global Shared variables are shared between user
>> sessions. It
>> means that if there will be multiple users using the app in the same
>> time, they will affect each other.
> So, should I declare it as "static" or as simple global variable
> (without "shared")?

You should probably store it in Session rather than declaring it "Global
Shared"

--
Microsoft MVP - ASP/ASP.NET
Please reply to the newsgroup. This email account is my spam trap so I
don't check it very often. If you must reply off-line, then remove the
"NO SPAM"

System.NullReferenceException: Object reference not set to an instance of an object.

Hi, the following code received run-time error (NullReferenceException), and I don't know how to troubleshoot it :(
under Page_Load at Default.aspx:
loginBox.LoginAuthenticated += new LoginAuthenticatedEventHandler(Succeeded)
under my LoginBox.ascx.cs, I setup the object like the followings:
public delegate void LoginAuthenticatedEventHandler(object sender, LoginAuthenticatedEventArgs e);
public event LoginAuthenticatedEventHandler LoginAuthenticated;
public class LoginAuthenticatedEventArgs : EventArgs
{
public int UsrID;
}//end class LoginAuthenticatedEventArgs

under my Page_Load of my LoginBox.ascx.cs, I load my object like this:
if (LoginAuthenticated != null)
{
LoginAuthenticatedEventArgs eventInfo = new LoginAuthenticatedEventArgs();
eventInfo.UsrID = Int32.Parse(txtUser.Text);
LoginAuthenticated(Page, eventInfo);
}//end if (LoginAuthenticated != null)

I thought I had the object reference to the correct place, what else am I missing?
TIA
..resoloved: http://forums.asp.net/1089126/ShowPost.aspx

System.NullReferenceException: Object reference not set to an instance of an object.

Hi all,

I have the following peice of code:

Esssentially, a querystring containing a comma separated list of values is
used to populate the appropriate intSectionID property of a user control.

<% If Not(Request.QueryString("SectionID") Is Nothing) Then %
<% arrSectionID = Split(Request.QueryString("SectionID"), ",") %>
<Company:Links ID="LevelTwo" intSectionID="<%# arrSectionID(0) %>"
Runat="Server"/
<% End If %
However i keep gettting the error listed in my post..

Can someone fill me in on what could be going wrong?

I have a suspicion it may be occuring when the User Controls DataBind method
is called.
The variable is visible to the parent page, but not the user control??

Suggest a way to fix?

Cheers,
AdamAdam,
This is aspnet user group. <%# %> code is ASP. Yes a few things are still
used <% %> this is only available for backwards compatibility not new
development.
Use the page_load or Page_render events for processing the querry string
into your control.

Bad luck

"Adam Knight" wrote:

> Hi all,
> I have the following peice of code:
> Esssentially, a querystring containing a comma separated list of values is
> used to populate the appropriate intSectionID property of a user control.
> <% If Not(Request.QueryString("SectionID") Is Nothing) Then %>
> <% arrSectionID = Split(Request.QueryString("SectionID"), ",") %>
> <Company:Links ID="LevelTwo" intSectionID="<%# arrSectionID(0) %>"
> Runat="Server"/>
> <% End If %>
> However i keep gettting the error listed in my post..
> Can someone fill me in on what could be going wrong?
> I have a suspicion it may be occuring when the User Controls DataBind method
> is called.
> The variable is visible to the parent page, but not the user control??
> Suggest a way to fix?
> Cheers,
> Adam
>

System.NullReferenceException: Object reference not set to an instance of an object.

I am getting the following error message when I am trying to calculate the value of textboxes. What am I doing wrong?

System.NullReferenceException: Object reference not set to an instance of an object.
line: finalVal = finalVal + Convert.ToInt64(strAI.Text)
Code--------

' Grab the textbox values of the interest cost table, loop through them adding up the values and displaying the totals

PrivateSub btnInterestCostTotal_Click(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Handles btnInterestCostTotal.Click

'AddField(DS_Term.Text)

Dim C, NAsInteger

'Find the txtAnnualInterestTotal textbox

Dim AITAs TextBox =CType(myTable.FindControl("txtAnnualInterestTotal"), TextBox)

Dim finalValAs Int64 = 0

'Loop through the dynamic textboxes

For C = 0ToCInt(DS_Term.Text) - 1

N = N + 1

Dim strAIAs TextBox =CType(myTable.FindControl("txtAnnualInterest" & N), TextBox)

'Add all the dynamic textboxes up

finalVal = finalVal + Convert.ToInt64(strAI.Text)

Next

'Display the total value in the txtAnnualInterestTotal textbox

AIT.Text = Convert.ToString(finalVal)

EndSub
code------------

Are you adding the textboxes dynamicaly? If so, you have to readd them on every postback.

I believe I am. Here is the code I am adding to the Page Init. Am I corrected adding them?

Sub createDynamicFields()

' Create the table and the controls based on the Term(# of years)

Dim IAsInteger

Dim intCounterAs Int64

If DS_Term.Text <> ""Then

For I = 0ToCInt(DS_Term.Text) - 1

Dim lblFiscalYearAs LiteralControl =New LiteralControl

Dim txtTextBoxAs TextBox =New TextBox

Dim txtTextBox2As TextBox =New TextBox

Dim txtTextBox3As TextBox =New TextBox

Dim tRow2As TableRow =New TableRow

Dim tCell1As TableCell =New TableCell

Dim tCell2As TableCell =New TableCell

Dim tCell3As TableCell =New TableCell

Dim tCell4As TableCell =New TableCell

' Grab Fiscal Year from tbBeginngingFiscalYear and Incurment the date by the DS_BondTerm field

lblFiscalYear.ID = "lblFiscalYear" & I + 1

lblFiscalYear.Text = Convert.ToString(Convert.ToInt64(DS_BeginningFiscalYear.Text) + I)

'**********************************

'Set the column width and

txtTextBox.Columns = 15

txtTextBox2.Columns = 15

txtTextBox3.Columns = 15

'Assign the textboxes IDs

txtTextBox.ID = "txtInterest" & I + 1

txtTextBox2.ID = "txtOsPrincipal" & I + 1

txtTextBox3.ID = "txtAnnualInterest" & I + 1

'Assign pre-defined values

'txtTextBox.Text = CStr(I + 1)

'txtTextBox2.Text = CStr(I + 1)

'txtTextBox3.Text = CStr(I + 1)

'Assign the cells to a row

tRow2.Cells.Add(tCell1)

tRow2.Cells.Add(tCell2)

tRow2.Cells.Add(tCell3)

tRow2.Cells.Add(tCell4)

'Assign the row to the table

myTable.Rows.Add(tRow2)

'Create the new controls

tCell1.Controls.Add(lblFiscalYear)

tCell2.Controls.Add(txtTextBox)

tCell3.Controls.Add(txtTextBox2)

tCell4.Controls.Add(txtTextBox3)

'Add the table to the placeholder

plhBondTerms.Controls.Add(myTable)

myTable.CellPadding = 0

myTable.CellSpacing = 0

'intCounter = intCounter + 1

'ViewState("Count") = intCounter

Next I

' ************************************

EndIf

EndSub


you should call this method on every postback

System.NullReferenceException: Object reference not set to an instance of an object.

This is the error message I get:
System.NullReferenceException: Object reference not set to an instance of an object.
at MyStore.CustomerFunctions.getCustomerOrders(String CustomerID)
at MyStore.Customer_Orders.Page_Load(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain()
And this is my code:

PublicSharedFunction getCustomerOrders(ByVal CustomerIDAsString)As OrderCollection

Dim strSQLAsString
Dim m_strConnectionStringAsString
Dim MyReaderAs SqlDataReader
Dim mySqlParaAs SqlParameter
Dim MyOrdersAsNew OrderCollection

m_strConnectionString = ConfigurationSettings.AppSettings("ConnectionString_checkout")

strSQL = "sp_WWWgetCustomerOrders"

mySqlPara =New SqlParameter("@dotnet.itags.org.CustomerID", CustomerID)

Try
MyReader = SqlHelper.ExecuteReader(m_strConnectionString, CommandType.StoredProcedure, strSQL, mySqlPara)
MyOrders.Fill(MyReader)

Catch exAs Exception
' Rethrow Exception for the moment
Throw ex

Finally
MyReader.Close()
MyReader =Nothing

EndTry

Return MyOrders

EndFunction


Code that calls the method:

DimaCustomerAs Customer
Dim MyOrdersAs OrderCollection
aCustomer =CType(HttpContext.Current.User, CustomPrincipal).Customer

MyOrders = CustomerFunctions.getCustomerOrders(aCustomer.CustomerID)

If MyOrders.Count > 0Then
Me.rptOpenRecentOrders.DataSource = MyOrders
Me.rptOpenRecentOrders.DataBind()
pnlNoOrdersToDisplay.Visible =False
Else
pnlNoOrdersToDisplay.Visible =True
EndIf

I only get the error occasionally at busy times on the internet, the Stored Proc is valid the connection string is valid because it works some times. The problem is not incorrect data being passed because if no data or incorrect data is past a different exception will be displayed because I have tested. I have no idea why this is happening, I have a feeling its to do with SQL Server because it only happens when it is at its busiest.
If the Stored Proc returns an empty reader there is no error, I have alreadyinitialized My returning object (the Orders Collection) so it shouldn't matter.
I know that the customer id is valid because I have an email sent to me if there is an error in the application via the globalApplication_Errormethod, it gets the customer id from the currently logged in person
Dim aCustomerAs Customer =CType(HttpContext.Current.User, CustomPrincipal).Customer
strCustID = aCustomer.CustomerID
This is displayed correctly when emailed. As I say this only happens at busy times and I am pulling my hair out to identify whats happening, can any one help?
Cheers
Scott


elbandit--
Regarding this...

elbandit wrote:

...As I say this only happens at busy times and I am pulling my hair out to identify whats happening, can any one help?


...I am wondering-- exactly what line is causing the error?
(The line can be discovered by doing a step-through of the code.)
I am going to guess that it is this line...
Do While MyReader.Read = True
...that causes the error.
If so, then you may be able to check for Nothing before the operation, like this...
If (MyReader Is Nothing) Then
'Reader cannot be used, probably due to a database connection issue.
'Maybe retry 1x automatically and if no connection then show message to user and ask the user to retry.
Else
Do While MyReader.Read = True
'Continue.
End If
...which may or may not work based on your use case.
HTH.
Thank you.
--Mark Kamoski
Sorry Mark I posted the wrong function, I have now editied. Please can you have another look,
Thanks
Scott
i can not see in your code
Dim con as New Sqlconenction(connection string her)

is it some where else or that what you miss!!??
elbandit--
Regarding this...

elbandit wrote:

Sorry Mark I posted the wrong function, I have now editied. Please can you have another look...


...I still think that the issue may be that the Reader is not getting instantiated properly when then database is too busy. As I mentioned above, you may need to check for null (Nothing) before using it.
If the database is busy, you may need to increase the timeout (a property on the connection string, seehttp://www.ConnectionStrings.com for details).
Alternately, if the database is really busy maybe your licensing has reached the maximum number of of connections and that's why the Reader is not instantiated properly.
Another idea would be to use a DataAdapter and a DataSet. Yours is a simple case and these objects might be a bit more stable given that the Reader stays open until it is closed and you really do not need an open connection to the database in this case.
The code looks something like this...
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand(COMMAND_TEXT, myConnection);
System.Data.OleDb.OleDbDataAdapter myDataAdapter = new System.Data.OleDb.OleDbDataAdapter(myCommand);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet);
...or you can seehttp://www.WebLogicArts.com/DemoReadingData01.aspx for a full working sample with all the code.
HTH.
Thank you.
--Mark Kamoski

Thanks Mark, I think you are probably right, as it only errors in busy periods I have changed the code to:

MyReader = SqlHelper.ExecuteReader(m_strConnectionString, CommandType.StoredProcedure, strSQL, mySqlPara)

If MyReaderIsNothingThen
Email.sendEmail()
EndIf
MyOrders.Fill(MyReader)

This way it will still error but I will get an email if the problem is that the reader is null, then I will be able to test with populating a dataset then populating my custom collection from that. The reason I didn't do it like that to begin with is that I thought a reader populated a dataset, but I guess if that is true the reader will populate a dataset faster than could populate my custom collection and therefore no error.
I will check out the time out property as well and let you know how I got on, and post the code that works. Cheers.
Thanks for the replies
Scott
P.S.
Fadil, I use MS Data Access Application Block to handle all connections to the database and opening the database and closing it is all done within in the most effiecient manner take a look athttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/daab.asp for more info.

System.NullReferenceException: Object reference not set to an instance of an object.

System.NullReferenceException: Object reference not set to an instance of an object.

This is the error i am getting, it says to review the stack trace. Here is the stack trace with code from my vb file below.

Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Manager.bindData(String sortExpression) +52
Manager.Page_Load(Object sender, EventArgs e) +13
System.Web.UI.Control.OnLoad(EventArgs e) +55
System.Web.UI.Control.LoadRecursive() +27
System.Web.UI.Page.ProcessRequestMain() +750

Private Sub Page_Load(ByVal sender As System.Object, ByVal e as System.EventArgs) Handles MyBase.Load
If not ispostback then
bindData("BugFind.BugID")
End If
end sub

Private Sub bindData(ByVal sortExpression as String)
Dim uEmail as string
uEmail = Session("Email").ToString()
dim conn as OleDbConnection
dim adapter as OleDbDataAdapter
dim mydataset as DataSet
dim connstring, query as string

Try
connstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="& server.mappath("Database.mdb")
conn = new OleDbConnection(connstring)
conn.Open()
query = "Select [Products].[ProductName], [BugFind].[FeatureName], [BugFind].[FinderEmail], [BugFind].[BuildNumber], [BugFind].[MajorReleaseNumber], [BugFind].[MinorReleaseNumber], [BugFind].[FindDate], [BugFind].[BugID], [BugFind].[FindTime] FROM [BugFind], [Products] where [BugFind].[ProductID] = [Products].[Product ID] and [Products].[ManagerEmail] = ('" & uEmail & "') ORDER BY " & sortExpression

adapter = new OleDbDataAdapter(query, conn)
mydataset = new dataset
adapter.Fill(mydataset)
BugsAssigned.DataKeyField = "BugID"
BugsAssigned.DataSource = mydataset
BugsAssigned.DataBind()

Finally
If (not isnothing(conn)) then
conn.close()
End if
End Try
End Sub

I really need help, because this is happening on another page of mine also and its head wrecking. I can't fix it.couple things to check...

::uEmail = Session("Email").ToString()

if Email does not exist in your session, your uEmail will be null/nothing

::BugsAssigned.DataKeyField = "BugID"

What is BugsAssigned, and does it exist (i.e. was an instance created...)?
Hey cheers for the reply. I have changed the uEmail string to a hard coded email address fopr the time being. You brought to my attention:

BugsAssigned.DataKeyField = "BugID"

What is BugsAssigned, and does it exist (i.e. was an instance created...)?

BugAssigned was an incorrect id for my DataGrid. It should be BugTable, but when i renamed it to BugTable it gave me this error:

Name 'BugTable' is not declared.

mydataset = new dataset

Line 46: adapter.Fill(mydataset)
Line 47: BugTable.DataKeyField = "BugID"
Line 48: BugTable.DataSource = mydataset
Line 49: BugTable.DataBind()
Hey cheers for the reply. I have changed the uEmail string to a hard coded email address fopr the time being. You brought to my attention:

BugsAssigned.DataKeyField = "BugID"

What is BugsAssigned, and does it exist (i.e. was an instance created...)?

BugAssigned was an incorrect id for my DataGrid. It should be BugTable, but when i renamed it to BugTable it gave me this error:

Name 'BugTable' is not declared.

mydataset = new dataset

Line 46: adapter.Fill(mydataset)
Line 47: BugTable.DataKeyField = "BugID"
Line 48: BugTable.DataSource = mydataset
Line 49: BugTable.DataBind()
Well, where did you declare BugTable?
its ok, i fixed the problem. BugTable was spelled wrongly for the id of my datagrid.cheers for the help guys

System.NullReferenceException: Object reference not set to an instance of an object.

can someone please shed some light in this please

rgs

Tony

Server Error in '/' Application.
------------------------

Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


<%@dotnet.itags.org. Page Language="VB" %>
<%@dotnet.itags.org. import Namespace="System.Data" %>
<%@dotnet.itags.org. import Namespace="System.Data.sqlclient" %>
<%@dotnet.itags.org. import Namespace="System.Web.Mail" %
<script runat="server"
Dim dataSet As System.Data.DataSet

Sub Button1_Click(sender As Object, e As EventArgs)
'dim dataseta as new dataset
dim pw as string = "apple21"

call MyQueryMethod(pw)
'
If dataset.Tables(0).rows.count <> 0 then response.write("hello")

'response.write(dataset.tables(0).rows(0).item(0))

End Sub
Function MyQueryMethod(ByVal password As String) As System.Data.DataSet
Dim connectionString As String = "server=xxxxx.87.xxx.xxx; user id=xxxx.150'; password=xxxxxx; database=xxxxx"& _
"xxxx.150'"
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

Dim queryString As String = "SELECT [tblReg].[UserName], [tblReg].[Password] FROM [tblReg] WHERE ([tblReg].[Pa"& _
"ssword] = @dotnet.itags.org.Password)"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dbParam_password As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_password.ParameterName = "@dotnet.itags.org.Password"
dbParam_password.Value = password
dbParam_password.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_password)

Dim dataAdapter As System.Data.IDbDataAdapter = New System.Data.SqlClient.SqlDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As System.Data.DataSet = New System.Data.DataSet
dataAdapter.Fill(dataSet)

'Return dataSet
End Function

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button>
<!-- Insert content here -->
</form>
</body>
</html

Might be this line:


If dataset.Tables(0).rows.count <> 0 then response.write("hello")

If the dataset or dataset table is nothing then you cannot get the count...might check that the dataset & table exists first, before trying to get the count.

Anyway, looks like your dataset will never get filled with this code as your Return Dataset line is commented out in the function MyQueryMethod...

MajorCats

System.NullReferenceException: Object reference not set to an instance of an object.

I'm getting this error in my ASP.NET 2.0 web application when I fire following line in my code:

xmlWriter1.WriteRaw(Session["TempForm"].ToString());

Can someone tell me what am I missing ?

Does the session object TempForm exist?

I would change that code to the below and see if you still get the exception. If you do, then the issue is with xmlWriter1. If not, then it's your session variable.

string tempForm = Session["TempForm"] as string;

if (tempForm != null)
{
xmlWriter1.WriteRaw(tempForm);
}

HTH,
Ryan


Thanks Ryan, Its working now !!!

System.NullReferenceException: Object reference not set to an instance of an object.

Hello:

I have a component that returns a value from a Sql Count statement... unfortunately I get the following error: System.NullReferenceException: Object reference not set to an instance of an object.

My component code:

Function GetCount(varAccountNumber as String) as String
conSqlConnect = New SqlConnection( "..." )
conSqlConnect.Open()
cmdSelect = New SqlCommand( "SELECT Count([account number]) AS Total From some_table Where [account number]=@dotnet.itags.org.accountnumber", conSqlConnect )
cmdSelect.Parameters.Add( "@dotnet.itags.org.accountnumber", varAccountNumber )
Return (cmdselect.executescalar())
conSqlConnect.Close()
End Function

on my code-behind page. I have

If myComponent.GetCount(user.identity.name) = 0 Then
'do something
End If

any suggestions?Which line caused this error?
>>Which line caused this error?

If myComponent.GetCount(user.identity.name) = 0 Then

What is "myComponent" ? It seems that it is not set correctly. Make sure that you initialize it the way it needs to be.
Yes I did initialize mycomponent like so:

Dim MyComponent as MyComponentClass
myComponent = New MyComponentClass()

any suggestions?
Either the component or the user.identity.name is causing the error. Try to debug the GetCount function of your component and also check if user.identity.name contains any value. At last I would say that debugging is the only way. Try quickwatch in Visual Studio.
Hope that it helped at least a little bit.

System.NullReferenceException: Object reference not set to an instance of an object.

I use VS.NET and yes I'm a beginner in ASP.NET.

Here is the problem:

in "%webroot%\components" is the folowing vb code file:

framework.vb
------------
Imports System
Imports System.Configuration
Imports System.Web
Imports System.Data
Imports System.Collections

Public Class framework
Public framework_name As String = "Hello"
Public framework_logo As String = ""
End Class
------------

Then in %webroot%\ is the main (test) page for the site:
default.aspx.vb (code behind file):
------------
Imports System.Web
Imports AIS3

Public Class _default
Inherits System.Web.UI.Page
Protected label1 As System.Web.UI.WebControls.Label
Protected maintitle As System.Web.UI.HtmlControls.HtmlGenericControl

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Init

Dim _framework As framework =
CType(HttpContext.Current.Items("framework"), framework)

label1.Text = _framework.framework_name

maintitle.InnerText = "New title for page"

End Sub
End Class
------------

There is no code in default.aspx and VS.NET creates the namespace
"AIS3" automatically. I imported it in default.aspx.vb file but im not
sure that was really needed.

But... when i run the thing i get:

------------
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.NullReferenceException: Object reference not
set to an instance of an object.

Source Error:

Line 26: Dim _framework As framework =
CType(HttpContext.Current.Items("framework"), framework)
Line 27:
Line 28: label1.Text = _framework.framework_name
Line 29:
Line 30: maintitle.InnerText = "New title for page"

Source File: c:\inetpub\wwwroot\AIS3\default.aspx.vb Line: 28

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an
object.]
AIS3._default.Page_Init(Object sender, EventArgs e) in
c:\inetpub\wwwroot\AIS3\default.aspx.vb:28
System.Web.UI.Control.OnInit(EventArgs e) +67
System.Web.UI.Control.InitRecursive(Control namingContainer) +241
System.Web.UI.Page.ProcessRequestMain() +174
-------------

Line 28 is marked

What am i doing wrong?

Thanku :)

PatrickDim _framework as new framework =
CType(HttpContext.Current.Items("framework"), framework)

"PatricQ" <patricq1@.yahoo.com> wrote in message
news:lft4309h49pe4tl6plotnfhkdk69vsbskj@.4ax.com...
> I use VS.NET and yes I'm a beginner in ASP.NET.
> Here is the problem:
> in "%webroot%\components" is the folowing vb code file:
> framework.vb
> ------------
> Imports System
> Imports System.Configuration
> Imports System.Web
> Imports System.Data
> Imports System.Collections
> Public Class framework
> Public framework_name As String = "Hello"
> Public framework_logo As String = ""
> End Class
> ------------
>
>
> Then in %webroot%\ is the main (test) page for the site:
> default.aspx.vb (code behind file):
> ------------
> Imports System.Web
> Imports AIS3
>
> Public Class _default
> Inherits System.Web.UI.Page
> Protected label1 As System.Web.UI.WebControls.Label
> Protected maintitle As System.Web.UI.HtmlControls.HtmlGenericControl
>
> Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
> System.EventArgs) Handles MyBase.Init
> Dim _framework As framework =
> CType(HttpContext.Current.Items("framework"), framework)
> label1.Text = _framework.framework_name
> maintitle.InnerText = "New title for page"
> End Sub
> End Class
> ------------
>
> There is no code in default.aspx and VS.NET creates the namespace
> "AIS3" automatically. I imported it in default.aspx.vb file but im not
> sure that was really needed.
> But... when i run the thing i get:
> ------------
> 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.NullReferenceException: Object reference not
> set to an instance of an object.
> Source Error:
>
> Line 26: Dim _framework As framework =
> CType(HttpContext.Current.Items("framework"), framework)
> Line 27:
> Line 28: label1.Text = _framework.framework_name
> Line 29:
> Line 30: maintitle.InnerText = "New title for page"
>
> Source File: c:\inetpub\wwwroot\AIS3\default.aspx.vb Line: 28
> Stack Trace:
>
> [NullReferenceException: Object reference not set to an instance of an
> object.]
> AIS3._default.Page_Init(Object sender, EventArgs e) in
> c:\inetpub\wwwroot\AIS3\default.aspx.vb:28
> System.Web.UI.Control.OnInit(EventArgs e) +67
> System.Web.UI.Control.InitRecursive(Control namingContainer) +241
> System.Web.UI.Page.ProcessRequestMain() +174
> -------------
>
> Line 28 is marked
>
> What am i doing wrong?
> Thanku :)
> Patrick
Thank you,

When I tried it, it said "end of statement expected", it doesnt like
the = Ctype(... part.

Patrick

On Tue, 17 Feb 2004 15:13:55 -0600, "A Lonely Programmer"
<SpamaLinuxUser@.NoSpamForMe.com> wrote:

> Dim _framework as new framework =
>CType(HttpContext.Current.Items("framework"), framework)
>
>"PatricQ" <patricq1@.yahoo.com> wrote in message
>news:lft4309h49pe4tl6plotnfhkdk69vsbskj@.4ax.com...
>> I use VS.NET and yes I'm a beginner in ASP.NET.
>>
>> Here is the problem:
>>
>> in "%webroot%\components" is the folowing vb code file:
>>
>> framework.vb
>> ------------
>> Imports System
>> Imports System.Configuration
>> Imports System.Web
>> Imports System.Data
>> Imports System.Collections
>>
>> Public Class framework
>> Public framework_name As String = "Hello"
>> Public framework_logo As String = ""
>> End Class
>> ------------
>>
>>
>>
>>
>>
>> Then in %webroot%\ is the main (test) page for the site:
>> default.aspx.vb (code behind file):
>> ------------
>> Imports System.Web
>> Imports AIS3
>>
>>
>> Public Class _default
>> Inherits System.Web.UI.Page
>> Protected label1 As System.Web.UI.WebControls.Label
>> Protected maintitle As System.Web.UI.HtmlControls.HtmlGenericControl
>>
>>
>> Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
>> System.EventArgs) Handles MyBase.Init
>>
>> Dim _framework As framework =
>> CType(HttpContext.Current.Items("framework"), framework)
>>
>> label1.Text = _framework.framework_name
>>
>> maintitle.InnerText = "New title for page"
>>
>> End Sub
>> End Class
>> ------------
>>
>>
>> There is no code in default.aspx and VS.NET creates the namespace
>> "AIS3" automatically. I imported it in default.aspx.vb file but im not
>> sure that was really needed.
>>
>> But... when i run the thing i get:
>>
>> ------------
>> 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.NullReferenceException: Object reference not
>> set to an instance of an object.
>>
>> Source Error:
>>
>>
>> Line 26: Dim _framework As framework =
>> CType(HttpContext.Current.Items("framework"), framework)
>> Line 27:
>> Line 28: label1.Text = _framework.framework_name
>> Line 29:
>> Line 30: maintitle.InnerText = "New title for page"
>>
>>
>> Source File: c:\inetpub\wwwroot\AIS3\default.aspx.vb Line: 28
>>
>> Stack Trace:
>>
>>
>> [NullReferenceException: Object reference not set to an instance of an
>> object.]
>> AIS3._default.Page_Init(Object sender, EventArgs e) in
>> c:\inetpub\wwwroot\AIS3\default.aspx.vb:28
>> System.Web.UI.Control.OnInit(EventArgs e) +67
>> System.Web.UI.Control.InitRecursive(Control namingContainer) +241
>> System.Web.UI.Page.ProcessRequestMain() +174
>> -------------
>>
>>
>>
>> Line 28 is marked
>>
>>
>> What am i doing wrong?
>>
>> Thanku :)
>>
>> Patrick
Never mind, I found it ;)

in global.asax ive put the folowing:

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As
EventArgs)
' Fires at the beginning of each request
Context.Items.Add("framework", New framework)
End Sub

The sub New() fills the framework class. But the Context.Items.Add
adds it to the HttpContext.Current.Items thingy...

PatricQ

On Tue, 17 Feb 2004 21:22:44 +0100, PatricQ <patricq1@.yahoo.com>
wrote:

>I use VS.NET and yes I'm a beginner in ASP.NET.
>Here is the problem:
>in "%webroot%\components" is the folowing vb code file:
>framework.vb
>------------
>Imports System
>Imports System.Configuration
>Imports System.Web
>Imports System.Data
>Imports System.Collections
>Public Class framework
> Public framework_name As String = "Hello"
> Public framework_logo As String = ""
>End Class
>------------
>
>
>Then in %webroot%\ is the main (test) page for the site:
>default.aspx.vb (code behind file):
>------------
>Imports System.Web
>Imports AIS3
>
>Public Class _default
>Inherits System.Web.UI.Page
>Protected label1 As System.Web.UI.WebControls.Label
>Protected maintitle As System.Web.UI.HtmlControls.HtmlGenericControl
>
>Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
>System.EventArgs) Handles MyBase.Init
> Dim _framework As framework =
>CType(HttpContext.Current.Items("framework"), framework)
> label1.Text = _framework.framework_name
> maintitle.InnerText = "New title for page"
> End Sub
>End Class
>------------
>
>There is no code in default.aspx and VS.NET creates the namespace
>"AIS3" automatically. I imported it in default.aspx.vb file but im not
>sure that was really needed.
>But... when i run the thing i get:
>------------
>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.NullReferenceException: Object reference not
>set to an instance of an object.
>Source Error:
>
>Line 26: Dim _framework As framework =
>CType(HttpContext.Current.Items("framework"), framework)
>Line 27:
>Line 28: label1.Text = _framework.framework_name
>Line 29:
>Line 30: maintitle.InnerText = "New title for page"
>
>Source File: c:\inetpub\wwwroot\AIS3\default.aspx.vb Line: 28
>Stack Trace:
>
>[NullReferenceException: Object reference not set to an instance of an
>object.]
> AIS3._default.Page_Init(Object sender, EventArgs e) in
>c:\inetpub\wwwroot\AIS3\default.aspx.vb:28
> System.Web.UI.Control.OnInit(EventArgs e) +67
> System.Web.UI.Control.InitRecursive(Control namingContainer) +241
> System.Web.UI.Page.ProcessRequestMain() +174
>-------------
>
>Line 28 is marked
>
>What am i doing wrong?
>Thanku :)
>Patrick

System.NullReferenceException: Object reference not set to an instance of an object.

Why do I get above error message while executing this code:
Public Sub DropDown_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Dim list As DropDownList = CType(sender, DropDownList)
Dim cell = CType(list.Parent, TableCell)
Dim item = CType(cell.Parent, DataGridItem)
Dim index = item.ItemIndex
Dim ds As DataSet
ds = DataGrid1.DataSource
Dim row As DataRow
row = ds.Tables(0).Select("ID = '" + item.Cells(0).Text + "'")(0)
'<-- ERROR
End SubSet a break point on the line
row = ds.Tables(0).Select("ID = '" + item.Cells(0).Text + "'")(0)
and see what is null there.
Could be:
no tables in ds;
no Cells(o) in item;
no item;
select doesn't return anything
...
Debug it.
Eliyahu
"John Smith" <john.smith@.microsoft.com> wrote in message
news:%Zahg.3487$oj5.1152205@.news.siol.net...
> Why do I get above error message while executing this code:
> Public Sub DropDown_SelectedIndexChanged(ByVal sender As System.Object,
> ByVal e As System.EventArgs)
> Dim list As DropDownList = CType(sender, DropDownList)
> Dim cell = CType(list.Parent, TableCell)
> Dim item = CType(cell.Parent, DataGridItem)
> Dim index = item.ItemIndex
> Dim ds As DataSet
> ds = DataGrid1.DataSource
> Dim row As DataRow
> row = ds.Tables(0).Select("ID = '" + item.Cells(0).Text + "'")(0)
> '<-- ERROR
> End Sub
>
Thank you.
"ds" was null. It seems I need to add DataSource into Session object
somehow. Beginner mistake. It seems DataGrid1.DataSource is not persistance?

> "ds" was null. It seems I need to add DataSource into Session object
> somehow. Beginner mistake. It seems DataGrid1.DataSource is not
> persistance?
I've declared ds as global Shared variable and it works fine so far.
Just note, that global Shared variables are shared between user sessions. It
means that if there will be multiple users using the app in the same time,
they will affect each other.
Eliyahu
"John Smith" <john.smith@.microsoft.com> wrote in message
news:tWbhg.3493$oj5.1152346@.news.siol.net...
>
> I've declared ds as global Shared variable and it works fine so far.
>

> Just note, that global Shared variables are shared between user sessions.
> It
> means that if there will be multiple users using the app in the same time,
> they will affect each other.
So, should I declare it as "static" or as simple global variable (without
"shared")?
What is your data source?
"John Smith" <john.smith@.microsoft.com> wrote in message
news:Dpchg.3498$oj5.1152406@.news.siol.net...
>
> So, should I declare it as "static" or as simple global variable (without
> "shared")?
>

> What is your data source?
XML
If you can't re-populate the datasource on every postback, you can store it
in a session variable.
Eliyahu
"John Smith" <john.smith@.microsoft.com> wrote in message
news:G7ehg.3500$oj5.1153527@.news.siol.net...
>
> XML
>

> If you can't re-populate the datasource on every postback, you can store
> it
> in a session variable.
There is no other way but session object?

Tuesday, March 13, 2012

System.Security.SecurityException: That assembly does not allow

I have created an ActiveX control that does word automation. Once I
creat an instance of work I get the following message
System.Security.SecurityException: That assembly does not allow
partially trusted callers.
I am using .net 2. I have a key and use the regasm tool after it the
dll is compiled
I am really lost on how to make this work any help will be appreciated
JohnDid this work for you?
I have a .NET class that i have made com visible and the client is
trying to access it using Visual Objects over a network shar and is
getting the same exception.
i have added the AllowPartiallyTusterCallers attribute to my
assemblyinfo.cs but is hasnt fixed it.
i have ben trying to test using something non .NET (VB 6.0) but i cant
even reference the tlb or dll but i think that is a VB 6.0 issue.
if anyone has any suggestions pleae let me know.
the Client has advised that the dll works if it is copied locally.
thanks

System.Security.SecurityException: That assembly does not allowpartially trusted callers.

I have created an ActiveX control that does word automation. Once I
creat an instance of work I get the following message
System.Security.SecurityException: That assembly does not allow
partially trusted callers.

I am using .net 2. I have a key and use the regasm tool after it the
dll is compiled

I am really lost on how to make this work any help will be appreciated

Johnyou prolly have to add this to your code:

[assembly: AllowPartiallyTrustedCallers]

--
Dominick Baier (http://www.leastprivilege.com)

Developing More Secure Microsoft ASP.NET 2.0 Applications (http://www.microsoft.com/mspress/books/9989.asp)

Quote:

Originally Posted by

I have created an ActiveX control that does word automation. Once I
creat an instance of work I get the following message
System.Security.SecurityException: That assembly does not allow
partially trusted callers.
>
I am using .net 2. I have a key and use the regasm tool after it the
dll is compiled
>
I am really lost on how to make this work any help will be appreciated
>
John
>