Results 1 to 2 of 2

Thread: InvalidCastException Error

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Mar 2002
    Posts
    68

    InvalidCastException Error

    I am trying to use an enumeration to limit the values an object can have. Anytime I try to assign a value using a string to the newly created object I get an casting exception error but when I use the numeric value it works fine. Can someone please help me solve this issue. The error and code are below.
    Thanks

    An unhandled exception of type 'System.InvalidCastException' occurred in microsoft.visualbasic.dll

    Additional information: Cast from string "Access" to type 'Integer' is not valid.


    Public Class DAL_Properties

    Private Enum DataStoreTypes
    SQLServer = 1
    Access = 2
    Flatfile = 3
    letsgetiton = 4
    End Enum


    Private _databaseName As String
    Private _dataSourceName As String
    Private _userName As String
    Private _password As String
    Private _connectionString As IDbConnection
    Private _command As IDbCommand
    Private _datastoreType As DataStoreTypes

    Public Property DatastoreType()
    Get
    Return _datastoreType
    End Get

    '*******************************************
    'Error Occurs Below
    '*******************************************
    Set(ByVal Value)
    _datastoreType = Value
    End Set
    End Property
    End Class

    Public Class DALTest
    Inherits System.Windows.Forms.Form
    Private Sub DALTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim babs As New DAL_Properties()

    babs.DatastoreType = "Access"
    MsgBox(babs.DatabaseName)
    MsgBox(babs.DatastoreType.ToString)
    Me.Close()

    End Sub
    End Class

  2. #2
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    An enum is stored as an integer so if you want to convert a string to its enum value then you can use Enum.Parse.
    VB Code:
    1. _datastoreType = [Enum].Parse(GetType(DataStoreTypes), "Access")

    Also you should declare your property types:
    VB Code:
    1. Public Property DatastoreType()[color=red][b] As DataStoreTypes[/b][/color]
    2. Get
    3. Return _datastoreType
    4. End Get
    5. Set(ByVal Value)
    6. _datastoreType = Value
    7. End Set
    8. End Property
    9. End Class

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width