Convert String input to working VB code - vb.net

Is it possible to convert, say, a textbox input to working code?
For example, user types 'if x<10 then y=2 else y=5' into textbox1, it gets used directly as code something like ...
dim x as integer = 5
dim y as integer = 0
include processed textbox1.text
resultbox.text = (y*20).tostring
It's not important why this would be needed - just whether there is any straight-forward method that parses a string to code.
Many thanks.

Maybe this is what you are looking for:
http://www.codeproject.com/Articles/12852/Compile-and-Run-VB-NET-Code-using-the-CodeDom

yes you can do this using the VBCodeProvider class. Although the amount of code required is quite significant:
http://www.codeproject.com/Articles/5472/Compiling-NET-code-on-the-fly

Related

Reverse number array multiline textboxes

basically, I want to reverse the numbers. (in the textbox there will be only 2-digit numbers)
if I have Textbox1.text:
12
2
41
71
70
I want to display in the box (Textbox1.text)
21
2
14
17
70
Function:
Public Shared Function Reverse(num As Integer) As Integer
Dim _reverse As Integer = 0
While num <> 0
_reverse *= 10
_reverse += num Mod 10
num \= 10
End While
Return _reverse
End Function
it should work, it actually works, but I don't know how to arrange it to work in all lines.
For Each lines In TextBox1.Lines
Dim rev = Reverse(lines)
lines.Replace(lines, rev)
Next
This is a perfect example of what happens when people try to write code without knowing what the code is supposed to. What the code is supposed to do is not just the end result but the steps to get there. If you don't know what the steps are then you shouldn't be writing any code because it's unlikely that what you write will do anything useful. Code is simply an implementation of logic so you should be getting the logic down first. It doesn't take any programming experience to work out the logic because we could all do this if it was a manual process and that would be the same logic.
So, what are the steps involved?
Get the lines of the text.
Loop over the lines.
Reverse the current line.
Replace the original line with the result of reversing.
Replace the text with the complete results.
If you actually consider each of those steps, it should be obvious that you cannot use a For Each loop because that will only let you get data out of a list, not put data into it. That would make it obvious that a For loop is the right choice, because will let you get data out and put it in. Now you can write code that actually does something useful.
Dim lines = TextBox1.Lines
For i = 0 To lines.GetUpperBound(0)
Dim line = lines(i)
Dim number = CInt(line)
Dim result = Reverse(number)
lines(i) = result.ToString()
Next
TextBox1.Lines = lines
Simple stuff but, again, if you don't know what the code has to actually do, writing code to do it is a challenge. Always break the problem down into smaller parts first, so you can work on each part individually, and always work out the logic you're trying to implement - and test that logic manually - before trying to write code to implement it.

Execute code block certain number of times

So i want to perform some code N times. N is textbox's value (e.g: 12).
I have no idea how to accomplish this, but something like this is on my mind:
For Each i as 1 in textbox1.text
'some code
Next
or
dim num1 as integer = 0
While num1 < textbox1.text
'some code
num1 += 1
Next
Those were just some ideas that were on my mind when i though about this question, none of above is tested nor tried to code.
Any ideas?
First and foremost, turn on Option Strict. This will save you time in the long run by converting possible runtime errors into compiler errors. At the top of the code file:
Option Strict On
It can also be set for the entire project:
Project Properties -> Compile Tab -> Option Strict selector: On
You can also make it the default for all new projects via:
Tools -> Options -> Projects and Solutions -> VB Defaults
What it Does
TextBox.Text always contains text (hence the clever names). "12" is just a string and is not the same as 12. So, before you can use it, you need to convert from string to integer. Note: If you want to restrict user input to numbers consider using a NumericUpDown.
There are several ways to convert, but considering that the data comes from a user, we have to allow that they may enter "I like pie" instead of numerals. So, we want to use the safest method which in this case is Integer.TryParse:
' declare int var to hold the result
Dim LoopCount As Integer
If Integer.TryParse(TextBox132.Text, LoopCount) Then
' success! LoopCOunt contains the integer value of the Text control
For n As Integer = 0 To LoopCount - 1
' some code to do something
Next
Else
' failed - scold the user with a MessageBox
End if
The comments in the code explain, but first you declare an integer variable to hold the converted value. Integer.TryParse is a function which will return True/False. If it succeeds, your variable will hold the integer value.
See Converting DataTypes for Option Strict for other convert methods and cases where they are appropriate.
This might work, I haven't tried:
Dim repeat_times as Integer = 0
Do Until repeat_times = 10 'times you want to repeat
repeat_times = repeat_times + 1
Console.WriteLine("Hello World") 'or anything you want
Loop
For n As Int32 = 0 To TextBox1.text - 1 was an answer for my question.

Conversion of VB Variable Types

I'm experimenting with learning how conversions work between variable types. Right now, I'm looking at using one conversion inside a Try/Catch (for values that can't convert). Is there a way to have a string representation of a value (obtained from a TextBox), convert it to a test type, and then see how that converts to all the other VB standard types in a loop? Or even better if there is a resource that already does this.
I can do this, but the code is very close to being repetitive and I'm hoping for a loop of some kind to simplify and shorten it.
First of all, there is no such thing as variable type in VB.net. May be you confusing with object variables - but this is not the same thing
Dim o As Object
o = 1 ' integer
The type that is stored in o is still integer. It is boxed.
Dim i As Integer = CInt(o)
You just un-boxed it. It works because object is lowest of types and all other derive from it. So, it can "box" any other type.
In UI we use text boxes to collect data. Text boxes can contain only string. And unless you writing these strings to a file like txt or xml you usually need to convert these strings to a type you use in application.
Dim port as Integer = Convert.ToInt32(txtPort.Text)
This is not really the area where you can determine, what type is in that text box. You really need to know upfront - what are you expecting there? You can test your text for being one type or another by using
Integer.TryParse
Date.TryParse
.....TryParse
.............
But the thing is, some data can successfully pass this test fro multiple types.
Good question. While it is possible to declare variables of type type and use them in a loop, these cannot be used in declarations or DirectCast.
Dim types() As Type = {GetType(Integer), GetType(Double)}
Dim testType As Type = GetType(Double)
The easiest way might be to test each value individually something like this (although you'll probably want a try-catch for each or all the items).
Dim xInteger As Integer
xInteger = TextBox1.Text
s &= "Integer: " & xInteger.ToString & vbcrlf ' or some test
Dim xDouble As Double
xDouble = TextBox1.Text
s &= "Double" & ": " & xDouble.ToString & vbcrlf
...

convert string to double in vb.net

data table contain column named as Fld_primary. this column contain value like 0.00 it is double datatype in mysql table.i want store that datatable value in double variable. am always getting error when i convert to double datatype.
my code
-------
Dim ds5 As dataset1.DTSUMDataTable = TA5.GetData(users)
Dim dttot As Double
dttot = CType(ds5("fld_primary").ToString, Double)
Error
Conversion from string "fld_primary" to type 'Integer' is not valid.
Edited # 3:01 AM with most recent screen caps.
Sometimes I find myself second guessing certain code based on people's answers, but I went ahead and took the time to check if the code that they are all using is even valid:
As you can see that code is a no go, so I used the correct code you see at the bottom there to reference a column.
However, if you wish to get a single cell use the chunk of code below that uses the foreach loop (the rest is my basic setup to show you how it works):
"Y" will equal the value of the datatable cell and you may convert it using the Double.Parse() method:
Dim y = Double.Parse(zDataRow("cat").ToString())
Be careful, if you have multiple rows you will notice that the value of y will change as it makes its way through all the rows.
you can convert it using the Convert class.
Dim dttot As Double = Convert.ToDouble(ds5("fld_primary"))
Your error is actually: ds5 expects an integer as a parameter, so using ds5("fld_primary") is not valid in your code. Perhaps you can try ds5(0)("fld_primary").
After you fixed it, use
dttot = Double.Parse(whatever_string_you_should_put_here)
If you cannot ensure your string must be a valid double, then use Double.TryParse.
You are better off using the 'Double.TryParse' way of converting as this handles any errors better and simply returns a boolean if succesful or not, using 'parse' will throw an exception which isnt anywhere near as elegant.
Dim dub as Double = 0
Double.TryParse("Your String Here", dub)
Try using Double.TryParse(text,value)
Try using this:
For a=0 to yourgridview.rows.count-1
Yourgridview.rows(a).cells(targetcolumnnumber).value=cdbl(Yourgridview.rows(a).cells(targetcolumnnumber).value)
Next

How can I read individual lines of a CSV file into a string array, to then be selectively displayed via combobox input?

I need your help, guys! :|
I've got myself a CSV file with the following contents:
1,The Compact,1.8GHz,1024MB,160GB,440
2,The Medium,2.4GHz,1024MB,180GB,500
3,The Workhorse,2.4GHz,2048MB,220GB,650
It's a list of computer systems, basically, that the user can purchase.
I need to read this file, line-by-line, into an array. Let's call this array csvline().
The first line of the text file would stored in csvline(0). Line two would be stored in csvline(1). And so on. (I've started with zero because that's where VB starts its arrays). A drop-down list would then enable the user to select 1, 2 or 3 (or however many lines/systems are stored in the file). Upon selecting a number - say, 1 - csvline(0) would be displayed inside a textbox (textbox1, let's say). If 2 was selected, csvline(1) would be displayed, and so on.
It's not the formatting I need help with, though; that's the easy part. I just need someone to help teach me how to read a CSV file line-by-line, putting each line into a string array - csvlines(count) - then increment count by one so that the next line is read into another slot.
So far, I've been able to paste the numbers of each system into an combobox:
Using csvfileparser As New Microsoft.VisualBasic.FileIO.TextFieldParser _
("F:\folder\programname\programname\bin\Debug\systems.csv")
Dim csvalue As String()
csvfileparser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
csvfileparser.Delimiters = New String() {","}
While Not csvfileparser.EndOfData
csvalue = csvfileparser.ReadFields()
combobox1.Items.Add(String.Format("{1}{0}", _
Environment.NewLine, _
csvalue(0)))
End While
End Using
But this only selects individual values. I need to figure out how selecting one of these numbers in the combobox can trigger textbox1 to be appended with just that line (I can handle the formatting, using the string.format stuff). If I try to do this using csvalue = csvtranslator.ReadLine , I get the following error message:
"Error 1 Value of type 'String' cannot be converted to '1-dimensional array of String'."
If I then put it as an array, ie: csvalue() = csvtranslator.ReadLine , I then get a different error message:
"Error 1 Number of indices is less than the number of dimensions of the indexed array."
What's the knack, guys? I've spent hours trying to figure this out.
Please go easy on me - and keep any responses ultra-simple for my newbie brain - I'm very new to all this programming malarkey and just starting out! :)
Structure systemstructure
Dim number As Byte
Dim name As String
Dim procspeed As String
Dim ram As String
Dim harddrive As String
Dim price As Integer
End Structure
Private Sub csvmanagement()
Dim systemspecs As New systemstructure
Using csvparser As New FileIO.TextFieldParser _
("F:\folder\programname\programname\bin\Debug\systems.csv")
Dim csvalue As String()
csvparser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
csvparser.Delimiters = New String() {","}
csvalue = csvparser.ReadFields()
systemspecs.number = csvalue(0)
systemspecs.name = csvalue(1)
systemspecs.procspeed = csvalue(2)
systemspecs.ram = csvalue(3)
systemspecs.harddrive = csvalue(4)
systemspecs.optical = csvalue(5)
systemspecs.graphics = csvalue(6)
systemspecs.audio = csvalue(7)
systemspecs.monitor = csvalue(8)
systemspecs.software = csvalue(9)
systemspecs.price = csvalue(10)
While Not csvparser.EndOfData
csvalue = csvparser.ReadFields()
systemlist.Items.Add(systemspecs)
End While
End Using
End Sub
Edit:
Thanks for your help guys, I've managed to solve the problem now.
It was merely a matter calling loops at the right point in time.
I would recommend using FileHelpers to do the reading.
The binding shouldn't be an issue after that.
Here is the Quickstart for Delimited Records:
Dim engine As New FileHelperEngine(GetType( Customer))
// To Read Use:
Dim res As Customer() = DirectCast(engine.ReadFile("FileIn.txt"), Customer())
// To Write Use:
engine.WriteFile("FileOut.txt", res)
When you get the file read, put it into a normal class and just bind to the class or use the list of items you have to do custom stuff with the combobox. Basically, get it out of the file and into a real class asap, then things will be easier.
At least take a look at the library. After using it, we use a lot more simple flat files since it is so easy, and we haven't written a file access routine since (for that kinda stuff).
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx
I think your main problem is understanding how arrays work (hence the error message).
You can use split and join functions to convert strings into and out of arrays
dim s() as string = split("1,2,3",",") gives and array of strings with 3 elements
dim ss as string = join(s,",") gives you the string back
Firstly, it's actually really good that you are using the TextFieldParser for reading CSV files - most don't but you won't have to worry about extra commas and quoted text etc...
The Readline method only gives you the raw string, hence the "Error 1 Value of type 'String' cannot be converted to '1-dimensional array of String'."
What you may find easier with combo boxes etc is to use an object (e.g. 'systemspecs') rather than strings. Assign the CSV data to the objects and override the "ToString" method of the 'systemspecs' class to display in the combo box how you want with formatting etc. That way when you handle the SelectedIndexChanged event (or similar) you get the "SelectedItem" from the combo box (which can be Nothing so check) and cast it as the 'systemspecs' to use it. The advantage is that you are not restricted to display the exact data in the combo etc.
' in "systemspecs"...
Public Overrides Function ToString() As String
Return Name ' or whatever...
End Function ' ToString
e.g.
dim item as new systemspecs
item.ID = csvalue(1)
item.Name = csvalue(2)
' etc...
combobox1.Items.Add(item)
Let me know if that makes sense!
PK :-)