473,513 Members | 2,469 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Create an object at runtime

I have a DataTable with three string columns, "Value", "Format" and "Type"

However, some of the rows contain numbers and dates in the Value field. So
I would like to be able to format the output based on the format specifier
in the Format field. The problem is, since the Value field is a string, it
doesnt properly "format".

So I need to convert to an object of the type specified by "Type"...ok, so
Activator.CreateInstance() BUT the problem is, the constructors dont take a
string argument.

So how do I create a new object of the specified type without knowing what
arguments it will need? There are no empty constructors that I can find.

I am mostly using DateTime, Single, Integer and String values as my "Type"

My weak attempt so far is shown below...any help is greatly appreciated.
Thanks

Dave Taylor

dv = CType(source.List, DataView)

drv = dv(rowNum)

szF = drv("Format")

szT = drv("Type")

szV = drv("Value")

'Convert the string to the appropriate type

If (szF <> "") Then

t = Type.GetType(szT)

v = Activator.CreateInstance(t) '**Error occurs here because of no 'empty
constructors' available

Try

v = szV

szV = Microsoft.VisualBasic.Format(v, szF)

Catch ex As InvalidCastException

'Ignore, just output the unformatted data if there is an error converting

End Try

End If

Nov 20 '05 #1
7 2201
Cor
Hi Dave,

Can you show the code with what you construct your datatable.

I do not how your sample deals with that datatable.

Cor
Nov 20 '05 #2
Cor,

The code I attached is placed in the Paint method of a
DataGridTextboxColumn-derived class. The DataTable and associated DataView
objects work just fine.

The problem I'm having is creating a new object at runtime given only a
string containing its type and no arguments for its constructor. So
basically, if the Type field contains "DateTime" or "System.DateTime" I want
to create a new DateTime object. The Activator.CreateInstance is supposed
to do this, however, it seems to require arguments specific to each type,
else it throws an exception. My idea was to create an empty object of the
specified type and then use implicit conversion to get the value from my
"Value" string.

regards,
Dave

"Cor" <no*@non.com> wrote in message
news:%2****************@TK2MSFTNGP09.phx.gbl...
Hi Dave,

Can you show the code with what you construct your datatable.

I do not how your sample deals with that datatable.

Cor

Nov 20 '05 #3
Cor
Hi Dave,

Where has that information to be.

In other words, is it a binded datagrid, is it back to the dataset.

That makes it difficult to see what you want.

I think I can understand the problem, but not the solution.

With a bounded datagrid, the "format" and "parse" events should work.
If not it seems to me a simple test of the value to know what has to be your
format.

But that is just from the information I got from you.

Because I do not understand why you needs the method you took.

Cor
Nov 20 '05 #4
"Dave Taylor" <no*********@processeng.com> schrieb
Cor,

The code I attached is placed in the Paint method of a
DataGridTextboxColumn-derived class. The DataTable and associated
DataView objects work just fine.

The problem I'm having is creating a new object at runtime given only
a string containing its type and no arguments for its constructor.
So basically, if the Type field contains "DateTime" or
"System.DateTime" I want to create a new DateTime object. The
Activator.CreateInstance is supposed to do this, however, it seems to
require arguments specific to each type, else it throws an exception.
My idea was to create an empty object of the specified type and then
use implicit conversion to get the value from my
"Value" string.


I think the problem is that you don't actually want to create a new object
and fill it by a value afterwards. You just want to convert a string to a
variable data type. So IMO the question is which conversion functions are
there and how can they be called dynamically? I'd create a new Sytem.Type
object depending on the String "System.DateTime" (or whatever). Then invoke
the Type object's parse method using reflection and passing the value
string. Afterwards call the ToString method and pass the format string. HTH.
--
Armin

How to quote and why:
http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html

Nov 20 '05 #5
Armin,

Thanks for the reply. The Parse() method was exactly what I needed...my
code now looks like this and works fine. Thanks again.
Protected Overloads Overrides Sub Paint(ByVal g As System.Drawing.Graphics,
ByVal bounds As System.Drawing.Rectangle, ByVal source As
System.Windows.Forms.CurrencyManager, ByVal rowNum As Integer, ByVal
backBrush As System.Drawing.Brush, ByVal foreBrush As System.Drawing.Brush,
ByVal alignToRight As Boolean)

Dim drv As DataRowView, dv As DataView

Dim v As Object, szV As String, szF As String, szT As String

Dim rect As Rectangle

dv = CType(source.List, DataView)

drv = dv(rowNum)

szF = drv("Format")

szT = drv("Type")

szV = drv("Value")

If InStr(szT, ".") = 0 Then szT = "System." & szT

'Convert the string to the appropriate type

If (szF <> "") Then

Try

v = Activator.CreateInstance(Type.GetType(szT))

v = v.Parse(szV)

szV = Microsoft.VisualBasic.Format(v, szF)

Catch ex As InvalidCastException

'Ignore just output the unformatted data if there is an error converting

End Try

End If

rect = bounds

g.FillRectangle(backBrush, rect)

rect.Offset(0, 2)

rect.Height -= 2

g.DrawString(szV, Me.DataGridTableStyle.DataGrid.Font, foreBrush,
RectangleF.FromLTRB(rect.X, rect.Y, rect.Right, rect.Bottom))

If _bOwnerDraw Then _ctl.Invalidate()

End Sub

"Armin Zingler" <az*******@freenet.de> wrote in message
news:e$**************@TK2MSFTNGP09.phx.gbl...
"Dave Taylor" <no*********@processeng.com> schrieb
Cor,

The code I attached is placed in the Paint method of a
DataGridTextboxColumn-derived class. The DataTable and associated
DataView objects work just fine.

The problem I'm having is creating a new object at runtime given only
a string containing its type and no arguments for its constructor.
So basically, if the Type field contains "DateTime" or
"System.DateTime" I want to create a new DateTime object. The
Activator.CreateInstance is supposed to do this, however, it seems to
require arguments specific to each type, else it throws an exception.
My idea was to create an empty object of the specified type and then
use implicit conversion to get the value from my
"Value" string.
I think the problem is that you don't actually want to create a new object
and fill it by a value afterwards. You just want to convert a string to a
variable data type. So IMO the question is which conversion functions are
there and how can they be called dynamically? I'd create a new Sytem.Type
object depending on the String "System.DateTime" (or whatever). Then

invoke the Type object's parse method using reflection and passing the value
string. Afterwards call the ToString method and pass the format string. HTH.

--
Armin

How to quote and why:
http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html

Nov 20 '05 #6
"Dave Taylor" <no*********@processeng.com> schrieb
Armin,

Thanks for the reply. The Parse() method was exactly what I
needed...my code now looks like this and works fine. Thanks
again.


Some comments:
- I'd strongly recommend to enable Option Strict in the project properties.
You have to change the code like this:

szF = drv("Format").ToString
szT = drv("Type").ToString
szV = drv("Value").ToString

- The brackets around the expression with the If statement is superfluous:
If szF <> "" Then
Even better because faster:
If szf.Length > 0 Then

- I'd also use expressive names. szF, szT, szV is not very intuitive

- What I meant was that you do not need to create an instance using
activator.createinstance. Here a modified example (no intuitive names...):

Dim szV As String, szF As String, szT As String
Dim Result As String
Dim t As Type
Dim o As Object

szF = "dd.MM.yyyy"
szT = "System.DateTime"
szV = "1/1/2004"

Try
t = Type.GetType(szT)
o = t.InvokeMember( _
"Parse", _
Reflection.BindingFlags.Static _
Or Reflection.BindingFlags.InvokeMethod _
Or Reflection.BindingFlags.Public, _
Nothing, Nothing, New Object() {szV} _
)
Result = t.InvokeMember( _
"ToString", Reflection.BindingFlags.Instance _
Or Reflection.BindingFlags.InvokeMethod _
Or Reflection.BindingFlags.Public, _
Nothing, o, New Object() {szF} _
).ToString
Catch ex As InvalidCastException
'Ignore just output the unformatted data if there is an error converting
End Try
--
Armin

How to quote and why:
http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html

Nov 20 '05 #7
Armin,

Thanks! I didnt quite get the not using CreateInstance part in your first
post, although using it worked as well. The InvokeMember works nicely too.

Thanks again
Dave
"Armin Zingler" <az*******@freenet.de> wrote in message
news:uH**************@TK2MSFTNGP12.phx.gbl...
"Dave Taylor" <no*********@processeng.com> schrieb
Armin,

Thanks for the reply. The Parse() method was exactly what I
needed...my code now looks like this and works fine. Thanks
again.

Some comments:
- I'd strongly recommend to enable Option Strict in the project

properties. You have to change the code like this:

szF = drv("Format").ToString
szT = drv("Type").ToString
szV = drv("Value").ToString

- The brackets around the expression with the If statement is superfluous:
If szF <> "" Then
Even better because faster:
If szf.Length > 0 Then

- I'd also use expressive names. szF, szT, szV is not very intuitive

- What I meant was that you do not need to create an instance using
activator.createinstance. Here a modified example (no intuitive names...):

Dim szV As String, szF As String, szT As String
Dim Result As String
Dim t As Type
Dim o As Object

szF = "dd.MM.yyyy"
szT = "System.DateTime"
szV = "1/1/2004"

Try
t = Type.GetType(szT)
o = t.InvokeMember( _
"Parse", _
Reflection.BindingFlags.Static _
Or Reflection.BindingFlags.InvokeMethod _
Or Reflection.BindingFlags.Public, _
Nothing, Nothing, New Object() {szV} _
)
Result = t.InvokeMember( _
"ToString", Reflection.BindingFlags.Instance _
Or Reflection.BindingFlags.InvokeMethod _
Or Reflection.BindingFlags.Public, _
Nothing, o, New Object() {szF} _
).ToString
Catch ex As InvalidCastException
'Ignore just output the unformatted data if there is an error converting End Try
--
Armin

How to quote and why:
http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html

Nov 20 '05 #8

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

Similar topics

4
22139
by: Tom Rathbun | last post by:
This is probably simple but it has stumped me. I want to create objects at runtime for example: A program that would allow you to draw lines on a form. For each new line I would like to create a new line object in an array the same way you would a simple variable. if it was just a variable I could dim a(0) as single ..
5
1480
by: Patrick Marti | last post by:
I wish to create some LinkButtons in DotNet. Because I will do it in dependence of the entries in a database, I can not add them with the mouse to the form as usually. I can create them in the Page_Load event but then I can not see them. I do not know the reason or how to do it correctly. Do anywhere know something about? For any help, I...
8
3168
by: Steve Neill | last post by:
Can anyone suggest how to create an arbitrary object at runtime WITHOUT using the deprecated eval() function. The eval() method works ok (see below), but is not ideal. function Client() { } Client.prototype.fullname = "John Smith"; var s = "Client"; eval("var o = new " + s + "();"); alert(o.fullname);
3
9128
by: takarimasu | last post by:
How can i create an input object (text area,select) at runtime ? B.
7
8823
by: dog | last post by:
I've seen plenty of articles on this topic but none of them have been able to solve my problem. I am working with an Access 97 database on an NT4.0 machine, which has many Access reports. I want my users to be able to select a report, click on a command button on a form, which will then automatically create the report as a pdf file and...
3
4309
by: equip200 | last post by:
I have a third party program that has the ability to control my program trough ActiveX/COM. My program is built in c#? What would I need to do to have the third party program connect to my program or just execute methods in my program? IS SOMETHING LIKE THIS THE CORRECT START AND WHATS NEEDED TO FOLLOW? AB = new...
15
26487
by: Amit D.Shinde | last post by:
I am adding a new picturebox control at runtime on the form How can i create click event handler for this control Amit Shinde
5
7348
by: Lance | last post by:
I need to create a Drawing.Bitmap from an array of integer values. My current technique creates a bitmap that eventually becomes corrupt (i.e., the bitmap's pixels change to a different color after a while). Can somebody please tell me what I'm doing wrong? Here is a sample: Public Shared Function CreateBitmapFromArray( _ ByVal width As...
2
3851
by: Christian Muggli | last post by:
can someone explain me how to create a app.config file during runtime? i see two ways: - add a skeleton of an app.config file to the exe/dll and extract it during runtime as a resource and extract OR - create a app.config file using xml is there another way?
0
7269
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
7394
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
7559
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
5701
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...
1
5100
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...
0
3248
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...
0
1611
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
1
811
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
470
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.