create array of integer from textbox - vb.net
I want to create an array of integer from textbox.
format string inside textbox is 80, 139, 22, 135, and more.
so far this is what I have.
This is working if textbox is 80 or 139 or 22 or any without "," or space
Dim XPort = {TxtScanPort.Text}.ToList
For Each BPort As Integer In XPort 'ERROR
Blahh.. blahh.. blahh..
but when I change value inside texbox to 80, 139, 135 then I get this error..
Conversion from string "80, 139, 135" to type 'Integer' is not valid.
then I am trying to convert string to integer.. like this..
Dim XPort = {TxtScanPort.Text}.ToList
Dim Str2Int = XPort.ConvertAll(Function(str) Int32.Parse(str)) 'ERROR
For Each BPort As Integer In Str2Int
Blahh.. blahh.. blahh..
then I have another error..
Input string was not in a correct format.
I have trying many code, but the most of them result same error "Input string was not in a correct format"
Not a fan of String.Split() (get a real CSV parser), but this is the quick'n'dirty option:
For Each BPort As Integer In TxtScanPort.Text.Split(",".ToCharArray()).Select(Function(i) CInt(i.Trim()))
Here is a method that should work if each value is delimited by a comma.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Values() As Integer = Array.ConvertAll(TxtScanPort.Text.Split(","c),
New Converter(Of String, Integer)(Function(input)
Dim output As Integer = 0
Integer.TryParse(input, output)
Return output
End Function))
For Each BPort As Integer In Values
Console.WriteLine(BPort)
Next
End Sub
End Class
The following code is that of ArrayDemo.xaml:
'Declarations:Nested_Buttons
Dim WM As Window=New Window:Dim canvas1 As Canvas=New Canvas
Dim vb As Viewbox = New Viewbox()
Dim btn1 As Button=New Button:Dim btn2 As Button=New Button
Dim Editor As TextBox=New TextBox
Dim ay0 As TextBox = New TextBox:Dim ay1 As TextBox = New TextBox
Dim ay2 As TextBox = New TextBox:Dim ay3 As TextBox = New TextBox
Dim ay4 As TextBox = New TextBox:Dim ay5 As TextBox = New TextBox
Dim ay6 As TextBox = New TextBox:Dim ay7 As TextBox = New TextBox
Dim ay8 As TextBox = New TextBox:Dim ay9 As TextBox = New TextBox
Dim ay10 As TextBox = New TextBox:Dim ay11 As TextBox = New TextBox
Dim ay12 As TextBox = New TextBox:Dim ay13 As TextBox = New TextBox
Dim ay14 As TextBox = New TextBox:Dim ay15 As TextBox = New TextBox
Dim ay16 As TextBox = New TextBox:Dim ay17 As TextBox = New TextBox
Dim ay18 As TextBox = New TextBox:Dim ay19 As TextBox = New TextBox
Dim ay20 As TextBox = New TextBox:Dim ay21 As TextBox = New TextBox
Dim ay22 As TextBox = New TextBox:Dim ay23 As TextBox = New TextBox
Dim ay24 As TextBox = New TextBox:Dim ay25 As TextBox = New TextBox
Dim ay26 As TextBox = New TextBox:Dim ay27 As TextBox = New TextBox
Dim ay28 As TextBox = New TextBox:Dim ay29 As TextBox = New TextBox
Dim ay30 As TextBox = New TextBox:Dim ay31 As TextBox = New TextBox
Dim i As Integer=Nothing:Dim j As Integer=Nothing:Dim k As Integer=Nothing
Dim gradientBrush3 As New LinearGradientBrush(Color.FromRgb(175,238,238),Color.FromRgb(255,255,0), _
New Point(0.5, 0),New Point(0.5, 1))
Sub New()
WM.Width=1900:WM.Height=1040:WM.Background=Brushes.MediumSlateBlue:WM.Content=vb:WM.Left=0:WM.Top=0
WM.Title="ArrayDemo":vb.Child=canvas1:canvas1.Width=1875:canvas1.Height=960
vb.Width=1600:vb.Height=950
btn1.Width=150:btn1.Height=60:btn1.Margin=New Thickness(0,0,0,0)
btn1.Background=New SolidColorBrush(Colors.Brown)
btn1.FontSize=20:btn1.Foreground=New SolidColorBrush(Colors.White)
btn1.HorizontalAlignment=System.Windows.HorizontalAlignment.Left
btn1.Content = New TextBlock With {.Text = "ArrayDemo", _
.TextWrapping = TextWrapping.Wrap}
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Array TextBoxes
ay0.Width=30:ay0.Height=43:ay0.Foreground=New SolidColorBrush(Colors.Black)
ay0.Background=gradientBrush3:ay0.FontSize=23
ay0.FontWeight=FontWeights.UltraBold:ay0.Text="0"
ay0.Margin=New Thickness(152,0,0,0)
ay1.Width=30:ay1.Height=43:ay1.Foreground=New SolidColorBrush(Colors.Black)
ay1.Background=gradientBrush3:ay1.FontSize=23
ay1.FontWeight=FontWeights.UltraBold:ay1.Text="1"
ay1.Margin=New Thickness(184,0,0,0)
ay2.Width=30:ay2.Height=43:ay2.Foreground=New SolidColorBrush(Colors.Black)
ay2.Background=gradientBrush3:ay2.FontSize=23
ay2.FontWeight=FontWeights.UltraBold:ay2.Text="1"
ay2.Margin=New Thickness(216,0,0,0)
ay3.Width=30:ay3.Height=43:ay3.Foreground=New SolidColorBrush(Colors.Black)
ay3.Background=gradientBrush3:ay3.FontSize=23
ay3.FontWeight=FontWeights.UltraBold:ay3.Text="3"
ay3.Margin=New Thickness(248,0,0,0)
ay4.Width=30:ay4.Height=43:ay4.Foreground=New SolidColorBrush(Colors.Black)
ay4.Background=gradientBrush3:ay4.FontSize=23
ay4.FontWeight=FontWeights.UltraBold:ay4.Text="1"
ay4.Margin=New Thickness(280,0,0,0)
ay5.Width=30:ay5.Height=43:ay5.Foreground=New SolidColorBrush(Colors.Black)
ay5.Background=gradientBrush3:ay5.FontSize=23
ay5.FontWeight=FontWeights.UltraBold:ay5.Text="1"
ay5.Margin=New Thickness(312,0,0,0)
ay6.Width=30:ay6.Height=43:ay6.Foreground=New SolidColorBrush(Colors.Black)
ay6.Background=gradientBrush3:ay6.FontSize=23
ay6.FontWeight=FontWeights.UltraBold:ay6.Text="21"
ay6.Margin=New Thickness(344,0,0,0)
ay7.Width=30:ay7.Height=43:ay7.Foreground=New SolidColorBrush(Colors.Black)
ay7.Background=gradientBrush3:ay7.FontSize=23
ay7.FontWeight=FontWeights.UltraBold:ay7.Text="9"
ay7.Margin=New Thickness(376,0,0,0)
ay8.Width=30:ay8.Height=43:ay8.Foreground=New SolidColorBrush(Colors.Black)
ay8.Background=gradientBrush3:ay8.FontSize=23
ay8.FontWeight=FontWeights.UltraBold:ay8.Text="9"
ay8.Margin=New Thickness(408,0,0,0)
ay9.Width=30:ay9.Height=43:ay9.Foreground=New SolidColorBrush(Colors.Black)
ay9.Background=gradientBrush3:ay9.FontSize=23
ay9.FontWeight=FontWeights.UltraBold:ay9.Text="1"
ay9.Margin=New Thickness(440,0,0,0)
ay10.Width=30:ay10.Height=43:ay10.Foreground=New SolidColorBrush(Colors.Black)
ay10.Background=gradientBrush3:ay10.FontSize=23
ay10.FontWeight=FontWeights.UltraBold:ay10.Text="3"
ay10.Margin=New Thickness(472,0,0,0)
ay11.Width=30:ay11.Height=43:ay11.Foreground=New SolidColorBrush(Colors.Black)
ay11.Background=gradientBrush3:ay11.FontSize=23
ay11.FontWeight=FontWeights.UltraBold:ay11.Text="3"
ay11.Margin=New Thickness(504,0,0,0)
ay12.Width=30:ay12.Height=43:ay12.Foreground=New SolidColorBrush(Colors.Black)
ay12.Background=gradientBrush3:ay12.FontSize=23
ay12.FontWeight=FontWeights.UltraBold:ay12.Text="3"
ay12.Margin=New Thickness(536,0,0,0)
ay13.Width=30:ay13.Height=43:ay13.Foreground=New SolidColorBrush(Colors.Black)
ay13.Background=gradientBrush3:ay13.FontSize=23
ay13.FontWeight=FontWeights.UltraBold:ay13.Text="1"
ay13.Margin=New Thickness(568,0,0,0)
ay14.Width=30:ay14.Height=43:ay14.Foreground=New SolidColorBrush(Colors.Black)
ay14.Background=gradientBrush3:ay14.FontSize=23
ay14.FontWeight=FontWeights.UltraBold:ay14.Text="5"
ay14.Margin=New Thickness(600,0,0,0)
ay15.Width=30:ay15.Height=43:ay15.Foreground=New SolidColorBrush(Colors.Black)
ay15.Background=gradientBrush3:ay15.FontSize=23
ay15.FontWeight=FontWeights.UltraBold:ay15.Text="5"
ay15.Margin=New Thickness(632,0,0,0)
ay16.Width=30:ay16.Height=43:ay16.Foreground=New SolidColorBrush(Colors.Black)
ay16.Background=gradientBrush3:ay16.FontSize=23
ay16.FontWeight=FontWeights.UltraBold:ay16.Text="31"
ay16.Margin=New Thickness(664,0,0,0)
ay17.Width=30:ay17.Height=43:ay17.Foreground=New SolidColorBrush(Colors.Black)
ay17.Background=gradientBrush3:ay17.FontSize=23
ay17.FontWeight=FontWeights.UltraBold:ay17.Text="11"
ay17.Margin=New Thickness(696,0,0,0)
ay18.Width=30:ay18.Height=43:ay18.Foreground=New SolidColorBrush(Colors.Black)
ay18.Background=gradientBrush3:ay18.FontSize=23
ay18.FontWeight=FontWeights.UltraBold:ay18.Text="9"
ay18.Margin=New Thickness(728,0,0,0)
ay19.Width=30:ay19.Height=43:ay19.Foreground=New SolidColorBrush(Colors.Black)
ay19.Background=gradientBrush3:ay19.FontSize=23
ay19.FontWeight=FontWeights.UltraBold:ay19.Text="1"
ay19.Margin=New Thickness(760,0,0,0)
ay20.Width=30:ay20.Height=43:ay20.Foreground=New SolidColorBrush(Colors.Black)
ay20.Background=gradientBrush3:ay20.FontSize=23
ay20.FontWeight=FontWeights.UltraBold:ay20.Text="3"
ay20.Margin=New Thickness(792,0,0,0)
ay21.Width=30:ay21.Height=43:ay21.Foreground=New SolidColorBrush(Colors.Black)
ay21.Background=gradientBrush3:ay21.FontSize=23
ay21.FontWeight=FontWeights.UltraBold:ay21.Text="1"
ay21.Margin=New Thickness(824,0,0,0)
ay22.Width=30:ay22.Height=43:ay22.Foreground=New SolidColorBrush(Colors.Black)
ay22.Background=gradientBrush3:ay22.FontSize=23
ay22.FontWeight=FontWeights.UltraBold:ay22.Text="3"
ay22.Margin=New Thickness(856,0,0,0)
ay23.Width=30:ay23.Height=43:ay23.Foreground=New SolidColorBrush(Colors.Black)
ay23.Background=gradientBrush3:ay23.FontSize=23
ay23.FontWeight=FontWeights.UltraBold:ay23.Text="7"
ay23.Margin=New Thickness(888,0,0,0)
ay24.Width=30:ay24.Height=43:ay24.Foreground=New SolidColorBrush(Colors.Black)
ay24.Background=gradientBrush3:ay24.FontSize=23
ay24.FontWeight=FontWeights.UltraBold:ay24.Text="51"
ay24.Margin=New Thickness(920,0,0,0)
ay25.Width=30:ay25.Height=43:ay25.Foreground=New SolidColorBrush(Colors.Black)
ay25.Background=gradientBrush3:ay25.FontSize=23
ay25.FontWeight=FontWeights.UltraBold:ay25.Text="5"
ay25.Margin=New Thickness(952,0,0,0)
ay26.Width=30:ay26.Height=43:ay26.Foreground=New SolidColorBrush(Colors.Black)
ay26.Background=gradientBrush3:ay26.FontSize=23
ay26.FontWeight=FontWeights.UltraBold:ay26.Text="1"
ay26.Margin=New Thickness(984,0,0,0)
ay27.Width=30:ay27.Height=43:ay27.Foreground=New SolidColorBrush(Colors.Black)
ay27.Background=gradientBrush3:ay27.FontSize=23
ay27.FontWeight=FontWeights.UltraBold:ay27.Text="1"
ay27.Margin=New Thickness(1016,0,0,0)
ay28.Width=30:ay28.Height=43:ay28.Foreground=New SolidColorBrush(Colors.Black)
ay28.Background=gradientBrush3:ay28.FontSize=23
ay28.FontWeight=FontWeights.UltraBold:ay28.Text="1"
ay28.Margin=New Thickness(1048,0,0,0)
ay29.Width=30:ay29.Height=43:ay29.Foreground=New SolidColorBrush(Colors.Black)
ay29.Background=gradientBrush3:ay29.FontSize=23
ay29.FontWeight=FontWeights.UltraBold:ay29.Text="1"
ay29.Margin=New Thickness(1080,0,0,0)
ay30.Width=30:ay30.Height=43:ay30.Foreground=New SolidColorBrush(Colors.Black)
ay30.Background=gradientBrush3:ay30.FontSize=23
ay30.FontWeight=FontWeights.UltraBold:ay30.Text="1"
ay30.Margin=New Thickness(1112,0,0,0)
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Array TextBoxes
Editor.TextWrapping=TextWrapping.Wrap:Editor.AcceptsReturn = True
Editor.Width=1840:Editor.Height=900:Editor.Margin=New Thickness(0,62,0,0)
Editor.Background=New SolidColorBrush(Colors.White)
Editor.Foreground=New SolidColorBrush(Colors.Navy)
Editor.FontSize=22:Editor.FontWeight=FontWeights.UltraBold
Editor.HorizontalScrollBarVisibility=ScrollBarVisibility.Visible
Editor.VerticalScrollBarVisibility=ScrollBarVisibility.Visible
Editor.HorizontalContentAlignment=HorizontalAlignment.Left
canvas1.Children.Add(btn1):canvas1.Children.Add(Editor)
canvas1.Children.Add(ay0):canvas1.Children.Add(ay1):canvas1.Children.Add(ay2)
canvas1.Children.Add(ay3):canvas1.Children.Add(ay4):canvas1.Children.Add(ay5)
canvas1.Children.Add(ay6):canvas1.Children.Add(ay7):canvas1.Children.Add(ay8)
canvas1.Children.Add(ay9):canvas1.Children.Add(ay10):canvas1.Children.Add(ay11)
canvas1.Children.Add(ay12):canvas1.Children.Add(ay13):canvas1.Children.Add(ay14)
canvas1.Children.Add(ay15):canvas1.Children.Add(ay16):canvas1.Children.Add(ay17)
canvas1.Children.Add(ay18):canvas1.Children.Add(ay19):canvas1.Children.Add(ay20)
canvas1.Children.Add(ay21):canvas1.Children.Add(ay22):canvas1.Children.Add(ay23)
canvas1.Children.Add(ay24):canvas1.Children.Add(ay25):canvas1.Children.Add(ay26)
canvas1.Children.Add(ay27):canvas1.Children.Add(ay28):canvas1.Children.Add(ay29)
canvas1.Children.Add(ay30)
AddHandler btn1.Click,AddressOf btn1Handler
WM.Show()
End Sub
Public Sub btn1Handler(sender As Object,e As EventArgs)
Try
Dim arr1() As Integer = {Integer.Parse(ay0.Text),Integer.Parse(ay1.Text),Integer.Parse(ay2.Text),Integer.Parse(ay3.Text), _
Integer.Parse(ay4.Text),Integer.Parse(ay5.Text),Integer.Parse(ay6.Text),Integer.Parse(ay7.Text), _
Integer.Parse(ay8.Text),Integer.Parse(ay9.Text),Integer.Parse(ay10.Text),Integer.Parse(ay11.Text), _
Integer.Parse(ay12.Text),Integer.Parse(ay13.Text),Integer.Parse(ay14.Text),Integer.Parse(ay15.Text), _
Integer.Parse(ay16.Text),Integer.Parse(ay17.Text),Integer.Parse(ay18.Text),Integer.Parse(ay19.Text), _
Integer.Parse(ay20.Text),Integer.Parse(ay21.Text),Integer.Parse(ay22.Text),Integer.Parse(ay23.Text), _
Integer.Parse(ay24.Text),Integer.Parse(ay25.Text),Integer.Parse(ay26.Text),Integer.Parse(ay27.Text), _
Integer.Parse(ay28.Text),Integer.Parse(ay29.Text),Integer.Parse(ay30.Text)}
Dim sName As Hashtable = New Hashtable
sName.Add(1,"pwBox"):sName.Add(2,"vwBox"):sName.Add(3,"canvas"):sName.Add(4,"tlbrTray"):
sName.Add(5,"menuStrip"):sName.Add(6,"menu"):sName.Add(7,"sbMenu"):sName.Add(8,"mnMenu")
sName.Add(9,"tlTip"):sName.Add(10,"grpBox"):sName.Add(11,"wrpPanel"):sName.Add(12,"dckPanel")
sName.Add(13,"ufrmGrid"):sName.Add(14,"expr"):sName.Add(15,"border"):sName.Add(16,"btn")
sName.Add(17,"label"):sName.Add(18,"tbx"):sName.Add(19,"Editor"):sName.Add(20,"listBox")
sName.Add(21,"rtxBox"):sName.Add(22,"cboBox"):sName.Add(23,"chkBox"):sName.Add(24,"rdoBtn")
sName.Add(25,"tglBtn"):sName.Add(26,"prgsBar"):sName.Add(27,"slider"):sName.Add(28,"scrlBar")
sName.Add(29,"cusContrl1"):sName.Add(30,"cusContrl2")
Dim ctrlName As Hashtable = New Hashtable
ctrlName.Add(1,"PasswordBox"):ctrlName.Add(2,"ViewBox"):ctrlName.Add(3,"Canvas"):ctrlName.Add(4,"ToolBarTray")
ctrlName.Add(5,"Menu"):ctrlName.Add(6,"MenuItem"):ctrlName.Add(7,"MenuItem"):ctrlName.Add(8,"MenuItem")
ctrlName.Add(9,"ToolTip"):ctrlName.Add(10,"GroupBox"):ctrlName.Add(11,"wrapPanel"):ctrlName.Add(12,"DockPanel")
ctrlName.Add(13,"UniformGrid"):ctrlName.Add(14,"Expander"):ctrlName.Add(15,"Border"):ctrlName.Add(16,"Button")
ctrlName.Add(17,"Label"):ctrlName.Add(18,"TextBox"):ctrlName.Add(19,"TextBox"):ctrlName.Add(20,"ListBox")
ctrlName.Add(21,"RichTextBox"):ctrlName.Add(22,"ComboBox"):ctrlName.Add(23,"CheckBox"):ctrlName.Add(24,"RadioButton")
ctrlName.Add(25,"ToggleButton"):ctrlName.Add(26,"ProgressBar"):ctrlName.Add(27,"Slider"):ctrlName.Add(28,"ScrollBar")
ctrlName.Add(29,"CustomControl"):ctrlName.Add(30,"CustomControl")
Try
For j=1 To 30 Step 1
Editor.Text &="Dim" & Space(1) & sName(j) & 1 & Space(1) & "As" & Space(1) & _
ctrlName(j) & "=New" & Space(1) & ctrlName(j) & VbCrLf
For i=1 To arr1(j)-1 Step 2
Editor.Text &="Dim" & Space(1) & sName(j) & i+1 & Space(1) & "As" & Space(1) & _
ctrlName(j) & "=New" & Space(1) & ctrlName(j) & ":" & _
"Dim" & Space(1) & sName(j) & i+2 & Space(1) & "As" & Space(1) & _
ctrlName(j) & "=New" & Space(1) & ctrlName(j) & VbCrLf
Next
Next
Catch ex As Exception
End Try
Catch ex As Exception
End Try
End Sub
The following file is that of ArrayDemo.vbproj:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{BE9B3350-5541-4EB5-BD4D-F6938B472E5E}</ProjectGuid>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>
<OutputType>WinExe</OutputType>
<RootNamespace>ArrayDemo</RootNamespace>
<AssemblyName>ArrayDemo</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<MyType>Custom</MyType>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<IncrementalBuild>true</IncrementalBuild>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>ArrayDemo.xml</DocumentationFile>
<NoWarn>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036,42314</NoWarn>
</PropertyGroup>
<ItemGroup>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="System.Core" />
<Reference Include="System.Windows" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="ArrayDemo.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
</ItemGroup>
<ItemGroup>
<Imports Include="System.Windows.Documents" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Collections" />
<Import Include="System.ComponentModel" />
<Import Include="Microsoft.VisualBasic" />
<Import Include="Microsoft.Win32" />
<Import Include="System.Windows.Application" />
<Import Include="System.IO" />
<Import Include="System" />
<Import Include="System.Web" />
<Import Include="System.Windows" />
<Import Include="System.Windows.Controls" />
<Import Include="System.Windows.Threading" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project>
compilation code from cmd--is given below--place the project folder with ArrayDemo.xaml and ArrayDemo.vbproj in D:\ drive--and call the compilation code from cmd. Your GUI will pop out on your screen--i have reduced the viewbox size to suit smaller screen sizes. If your screen size is different then readjust viewbox dimentions suitably.
Related
SSIS: Script task to write recordset to file
I am using SQL Server Data Tools 2013 to create an SSIS package. This package has an Execute SQL Task with a Full Resultset option to push the query results into an SSIS Variable, of type Object. I'm using the following in a script task to take a recordset stored in an object variable and write it to a CSV: Public Sub Main() Dim fileName As String = Dts.Variables("vFileName").Value.ToString Dim destinationPath As String = Dts.Variables("vDestinationPath").Value.ToString Dim destinationPathAndFileName As String = destinationPath + fileName Dim fileContents As String = "" Dim oleDB As OleDbDataAdapter = New OleDbDataAdapter() Dim table As DataTable = New DataTable() Dim rs As System.Object = Dts.Variables("vResultSet").Value ' Populate DataTable with vResultSet data oleDB.Fill(table, rs) ' Loop through columns and concatenate with commas For Each col As DataColumn In table.Columns fileContents &= col.ColumnName & "," Next ' Remove final comma from columns string and append line break fileContents = fileContents.Substring(0, fileContents.Length - 1) fileContents &= Environment.NewLine ' Loop through rows and concatenate with commas Dim i As Integer For Each row As DataRow In table.Rows For i = 1 To table.Columns.Count fileContents &= row(i - 1).ToString() & "," Next ' Remove final comma from row string and append line break fileContents = fileContents.Substring(0, fileContents.Length - 1) fileContents &= Environment.NewLine Next ' Write all text to destination file. If file exists, this step will overwrite it. System.IO.File.WriteAllText(destinationPathAndFileName, fileContents) Dts.TaskResult = ScriptResults.Success End Sub This works, but it's veeeery slow, like 25+ minutes to write a single 14k-row dataset to CSV. I can't use a data flow because this process exists in a loop, and the metadata for each table to be exported is different. I'm pretty sure a script task is the only option, but is there a faster way than looping through each row of the dataset? Please let me know if I can provide more info.
Feel free to translate to VB.NET as you see fit. Seeing as how I already have this code ~ written for a different project, I mashed your request in with how mine works Passing in 3 SSIS variables: vFileName, vDestinationPath and vResultSet, the code in Main will convert the ado recordset into a DataTable which is then added to a DataSet and passed to the Persist method. Persist has a default parameter for delimiter of |. This implementation does not attempt to deal with any of the corner cases, at all. It does not escape text columns with a qualifier, doesn't escape embedded qualifiers, do anything with newlines in the feeds and something in the OleDbDataAdapter's fill method fails with binary data, etc public void Main() { string fileName = Dts.Variables["User::vFileName"].Value.ToString(); DataSet ds = null; DataTable dt = null; string outputFolder = Dts.Variables["User::vDestinationPath"].Value.ToString(); string fileMask = string.Empty; string sheetName = string.Empty; string outSubFolder = string.Empty; string message = string.Empty; bool fireAgain = true; try { ds = new DataSet(); dt = new DataTable(); System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(); adapter.Fill(dt, Dts.Variables["User::vResultSet"].Value); string baseFileName = System.IO.Path.GetFileNameWithoutExtension(fileName); baseFileName = System.IO.Path.GetFileName(fileName); ds.Tables.Add(dt); //foreach (DataTable dt in ds.Tables) { Persist(ds, fileName, outputFolder); } } catch (Exception ex) { Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "fileName", fileName), string.Empty, 0, ref fireAgain); Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "outputFolder", outputFolder), string.Empty, 0, ref fireAgain); Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "ExceptionDetails", ex.ToString()), string.Empty, 0, ref fireAgain); Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "InnerExceptionDetails", ex.InnerException), string.Empty, 0, ref fireAgain); } Dts.TaskResult = (int)ScriptResults.Success; } public static void Persist(System.Data.DataSet ds, string originalFileName, string outputFolder, string delimiter = "|") { // Enumerate through all the tables in the dataset // Save it out as sub versions of the if (ds == null) { return; } string baseFileName = System.IO.Path.GetFileNameWithoutExtension(originalFileName); string baseFolder = System.IO.Path.GetDirectoryName(originalFileName); System.Collections.Generic.List<string> header = null; foreach (System.Data.DataTable table in ds.Tables) { string outFilePath = System.IO.Path.Combine(outputFolder, string.Format("{0}.{1}.csv", baseFileName, table.TableName)); System.Text.Encoding e = System.Text.Encoding.Default; if (table.ExtendedProperties.ContainsKey("Unicode") && (bool)table.ExtendedProperties["Unicode"]) { e = System.Text.Encoding.Unicode; } using (System.IO.StreamWriter file = new System.IO.StreamWriter(System.IO.File.Open(outFilePath, System.IO.FileMode.Create), e)) { table.ExtendedProperties.Add("Path", outFilePath); // add header row header = new System.Collections.Generic.List<string>(table.Columns.Count); foreach (System.Data.DataColumn item in table.Columns) { header.Add(item.ColumnName); } file.WriteLine(string.Join(delimiter, header)); foreach (System.Data.DataRow row in table.Rows) { // TODO: For string based fields, capture the max length IEnumerable<string> fields = (row.ItemArray).Select(field => field.ToString()); file.WriteLine(string.Join(delimiter, fields)); } } } } Need to run but a Biml implementation looks like <Biml xmlns="http://schemas.varigence.com/biml.xsd"> <Connections> <OleDbConnection Name="tempdb" ConnectionString="Data Source=localhost\dev2014;Initial Catalog=AdventureWorksDW2014;Provider=SQLNCLI11.0;Integrated Security=SSPI;"/> </Connections> <Packages> <Package Name="so_37059747" ConstraintMode="Linear"> <Variables> <Variable DataType="String" Name="QuerySource"><![CDATA[SELECT S.name , T.name FROM sys.schemas AS S INNER JOIN sys.tables AS T ON T.schema_id = S.schema_id;]]></Variable> <Variable DataType="String" Name="SchemaName">dbo</Variable> <Variable DataType="String" Name="TableName">foo</Variable> <Variable DataType="String" Name="QueryTableDump" EvaluateAsExpression="true">"SELECT X.* FROM [" + #[User::SchemaName] + "].[" + #[User::TableName] + "] AS X;"</Variable> <Variable DataType="Object" Name="rsTables"></Variable> <Variable DataType="Object" Name="vResultSet"></Variable> <Variable DataType="String" Name="vFileName" EvaluateAsExpression="true">#[User::SchemaName] + "_" + #[User::TableName] + ".txt"</Variable> <Variable DataType="String" Name="vDestinationPath">c:\ssisdata\so\Output</Variable> </Variables> <Tasks> <ExecuteSQL ConnectionName="tempdb" Name="SQL Generate Loop data" ResultSet="Full"> <VariableInput VariableName="User.QuerySource" /> <Results> <Result VariableName="User.rsTables" Name="0" /> </Results> </ExecuteSQL> <ForEachAdoLoop SourceVariableName="User.rsTables" Name="FELC Shred rs" ConstraintMode="Linear"> <VariableMappings> <VariableMapping VariableName="User.SchemaName" Name="0" /> <VariableMapping VariableName="User.TableName" Name="1" /> </VariableMappings> <Tasks> <ExecuteSQL ConnectionName="tempdb" Name="SQL Generate Export data" ResultSet="Full"> <VariableInput VariableName="User.QueryTableDump" /> <Results> <Result VariableName="User.vResultSet" Name="0" /> </Results> </ExecuteSQL> <Script ProjectCoreName="ST_RS2CSV" Name="SCR Convert to text"> <ScriptTaskProjectReference ScriptTaskProjectName="ST_RS2CSV" /> </Script> </Tasks> </ForEachAdoLoop> </Tasks> </Package> </Packages> <ScriptProjects> <ScriptTaskProject ProjectCoreName="ST_RS2CSV" Name="ST_RS2CSV" VstaMajorVersion="0"> <ReadOnlyVariables> <Variable Namespace="User" VariableName="vFileName" DataType="String" /> <Variable Namespace="User" VariableName="vDestinationPath" DataType="String" /> <Variable Namespace="User" VariableName="vResultSet" DataType="Object" /> </ReadOnlyVariables> <Files> <File Path="ScriptMain.cs" BuildAction="Compile"> <![CDATA[namespace DataDumper { using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml.Linq; using Microsoft.SqlServer.Dts.Runtime; [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute] public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase { public void Main() { string fileName = Dts.Variables["User::vFileName"].Value.ToString(); DataSet ds = null; DataTable dt = null; string outputFolder = Dts.Variables["User::vDestinationPath"].Value.ToString(); string fileMask = string.Empty; string sheetName = string.Empty; string outSubFolder = string.Empty; string message = string.Empty; bool fireAgain = true; try { ds = new DataSet(); dt = new DataTable(); System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(); adapter.Fill(dt, Dts.Variables["User::vResultSet"].Value); string baseFileName = System.IO.Path.GetFileNameWithoutExtension(fileName); baseFileName = System.IO.Path.GetFileName(fileName); ds.Tables.Add(dt); //foreach (DataTable dt in ds.Tables) { Persist(ds, fileName, outputFolder); } } catch (Exception ex) { Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "fileName", fileName), string.Empty, 0, ref fireAgain); Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "outputFolder", outputFolder), string.Empty, 0, ref fireAgain); Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "ExceptionDetails", ex.ToString()), string.Empty, 0, ref fireAgain); Dts.Events.FireInformation(0, "Data Dumper", string.Format("{0}|{1}", "InnerExceptionDetails", ex.InnerException), string.Empty, 0, ref fireAgain); } Dts.TaskResult = (int)ScriptResults.Success; } public static void Persist(System.Data.DataSet ds, string originalFileName, string outputFolder, string delimiter = "|") { // Enumerate through all the tables in the dataset // Save it out as sub versions of the if (ds == null) { return; } string baseFileName = System.IO.Path.GetFileNameWithoutExtension(originalFileName); string baseFolder = System.IO.Path.GetDirectoryName(originalFileName); System.Collections.Generic.List<string> header = null; foreach (System.Data.DataTable table in ds.Tables) { string outFilePath = System.IO.Path.Combine(outputFolder, string.Format("{0}.{1}.csv", baseFileName, table.TableName)); System.Text.Encoding e = System.Text.Encoding.Default; if (table.ExtendedProperties.ContainsKey("Unicode") && (bool)table.ExtendedProperties["Unicode"]) { e = System.Text.Encoding.Unicode; } using (System.IO.StreamWriter file = new System.IO.StreamWriter(System.IO.File.Open(outFilePath, System.IO.FileMode.Create), e)) { table.ExtendedProperties.Add("Path", outFilePath); // add header row header = new System.Collections.Generic.List<string>(table.Columns.Count); foreach (System.Data.DataColumn item in table.Columns) { header.Add(item.ColumnName); } file.WriteLine(string.Join(delimiter, header)); foreach (System.Data.DataRow row in table.Rows) { // TODO: For string based fields, capture the max length IEnumerable<string> fields = (row.ItemArray).Select(field => field.ToString()); file.WriteLine(string.Join(delimiter, fields)); } } } } enum ScriptResults { Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success, Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure }; } } ]]> </File> <File Path="Properties\AssemblyInfo.cs" BuildAction="Compile"> using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("AssemblyTitle")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Bill Fellows")] [assembly: AssemblyProduct("ProductName")] [assembly: AssemblyCopyright("Copyright # 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.*")] </File> </Files> <AssemblyReferences> <AssemblyReference AssemblyPath="System" /> <AssemblyReference AssemblyPath="System.Core" /> <AssemblyReference AssemblyPath="System.Data" /> <AssemblyReference AssemblyPath="System.Data.DataSetExtensions" /> <AssemblyReference AssemblyPath="System.Windows.Forms" /> <AssemblyReference AssemblyPath="System.Xml" /> <AssemblyReference AssemblyPath="Microsoft.SqlServer.ManagedDTS.dll" /> <AssemblyReference AssemblyPath="Microsoft.SqlServer.ScriptTask.dll" /> <AssemblyReference AssemblyPath="System.Linq" /> <AssemblyReference AssemblyPath="System.Xml.Linq" /> <AssemblyReference AssemblyPath="Microsoft.VisualBasic" /> </AssemblyReferences> </ScriptTaskProject> </ScriptProjects> </Biml> That dumped all of AdventureworksDW2014 in 15 seconds Based on the comment that this line is failing IEnumerable<string> fields = (row.ItemArray).Select(field => field.ToString()); Ensure that you have the following using statements in your project. I think those extensions are in the Linq namespaces but it could have been the Collections using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml.Linq; using Microsoft.SqlServer.Dts.Runtime; Why was the original slow? My assumption is the slowness boils down to all that concatenation. Strings are immutable in .Net and you are creating a new version of that string each time you add a column to it. When I build my line, I'm using the String.Join method to zip up each element an array into a single string. This also simplifies the logic required to append the field delimiters. I also immediately write the current line to a file instead of bloating my memory just to dump it all with a call to WriteAllText
This is the VB.NET version of #billinkc's excellent answer in case it's useful to anyone: Imports System Imports System.Data Imports System.Math Imports System.Collections Imports System.Collections.Generic Imports Microsoft.SqlServer.Dts.Runtime Imports System.Linq Imports System.Text Imports System.Windows.Forms Public Sub Main() Dim fileName As String = Dts.Variables("User::vFileName").Value.ToString() Dim ds As DataSet = Nothing Dim dt As DataTable = Nothing Dim outputFolder As String = Dts.Variables("User::vDestinationPath").Value.ToString() Dim fileMask As String = String.Empty Dim sheetName As String = String.Empty Dim outSubFolder As String = String.Empty Dim message As String = String.Empty Dim fireAgain As Boolean = True Try ds = New DataSet() dt = New DataTable() Dim adapter As New System.Data.OleDb.OleDbDataAdapter() adapter.Fill(dt, Dts.Variables("User::vResultSet").Value) Dim baseFileName As String = System.IO.Path.GetFileNameWithoutExtension(fileName) baseFileName = System.IO.Path.GetFileName(fileName) ds.Tables.Add(dt) 'foreach (DataTable dt in ds.Tables) If True Then Persist(ds, fileName, outputFolder) End If Catch ex As Exception Dts.Events.FireInformation(0, "Data Dumper", String.Format("{0}|{1}", "fileName", fileName), String.Empty, 0, fireAgain) Dts.Events.FireInformation(0, "Data Dumper", String.Format("{0}|{1}", "outputFolder", outputFolder), String.Empty, 0, fireAgain) Dts.Events.FireInformation(0, "Data Dumper", String.Format("{0}|{1}", "ExceptionDetails", ex.ToString()), String.Empty, 0, fireAgain) Dts.Events.FireInformation(0, "Data Dumper", String.Format("{0}|{1}", "InnerExceptionDetails", ex.InnerException), String.Empty, 0, fireAgain) End Try Dts.TaskResult = CInt(ScriptResults.Success) End Sub Public Shared Sub Persist(ds As System.Data.DataSet, originalFileName As String, outputFolder As String, Optional delimiter As String = ",") ' Enumerate through all the tables in the dataset ' Save it out as sub versions of the If ds Is Nothing Then Return End If Dim baseFileName As String = System.IO.Path.GetFileNameWithoutExtension(originalFileName) Dim baseFolder As String = System.IO.Path.GetDirectoryName(originalFileName) Dim header As System.Collections.Generic.List(Of String) = Nothing For Each table As System.Data.DataTable In ds.Tables Dim outFilePath As String = System.IO.Path.Combine(outputFolder, String.Format("{0}.csv", baseFileName, table.TableName)) Dim e As System.Text.Encoding = System.Text.Encoding.[Default] If table.ExtendedProperties.ContainsKey("Unicode") AndAlso CBool(table.ExtendedProperties("Unicode")) Then e = System.Text.Encoding.Unicode End If Using file As New System.IO.StreamWriter(System.IO.File.Open(outFilePath, System.IO.FileMode.Create), e) table.ExtendedProperties.Add("Path", outFilePath) ' add header row header = New System.Collections.Generic.List(Of String)(table.Columns.Count) For Each item As System.Data.DataColumn In table.Columns header.Add(item.ColumnName) Next file.WriteLine(String.Join(delimiter, header)) For Each row As System.Data.DataRow In table.Rows ' TODO: For string based fields, capture the max length Dim fields As IEnumerable(Of String) = (row.ItemArray).[Select](Function(field) field.ToString()) file.WriteLine(String.Join(delimiter, fields)) Next End Using Next End Sub
Input string was not in a correct format. Gridview
I am in the middle doing my school work however i having some error with my code but i run this similar code in my other file and there is no issue. Hope you guys can help me. It's about getting multi datakeyname <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" Width="100%" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging2" PageSize="3" CssClass="Grid" DataKeyNames="id, tripidtaking, reqid" > <Columns> <asp:BoundField DataField="fname" /> <asp:BoundField DataField="reqid" HeaderText="Req ID" /> <asp:BoundField DataField="tripidtaking" HeaderText="trip ID" /> <asp:BoundField DataField="id" HeaderText="trip ID" /> <asp:BoundField DataField="startptname" HeaderText="Origin" /> <asp:BoundField DataField="endptname" HeaderText="Destination" /> <asp:BoundField DataField="givendate" HeaderText="Date" /> <asp:BoundField DataField="starttime" HeaderText="Agreed Time" /> <asp:BoundField DataField="numperson" HeaderText="NoOfPpl" /> <asp:BoundField DataField="Recurring" HeaderText="Whether Recurring" /> <asp:BoundField DataField="day" HeaderText="Selected Day" /> <asp:BoundField DataField="usertype" HeaderText="Type" /> <asp:BoundField DataField="Cfname" HeaderText="Driver Name" /> <asp:BoundField DataField="cid" HeaderText="Driver ID" /> <asp:BoundField DataField="" HeaderText="" /> <asp:BoundField DataField="" HeaderText="" /> </Columns> </asp:GridView> Protected Sub GridView2_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound Dim row As GridViewRow = e.Row If row.RowType = DataControlRowType.DataRow Then Dim lb2 As New LinkButton() lb2.ID = "lbCancel" lb2.Text = "Cancel" lb2.CommandName = "CancelRow" lb2.CommandArgument = DataBinder.Eval(row.DataItem, "ID") row.Cells(14).Controls.Add(lb2) If row.Cells(13).Text = reqid Then Dim lb As New LinkButton() lb.ID = "lbEnd" lb.Text = "End" lb.CommandName = "EndRow" lb.CommandArgument = DataBinder.Eval(row.DataItem, "tripidtaking") + "," + DataBinder.Eval(row.DataItem, "reqid") row.Cells(15).Controls.Add(lb) End If End If End Sub Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView2.RowCommand Dim reqid As String = Session("reqid") Dim arguments As String() = e.CommandArgument.ToString().Split(New Char() {","}) If (e.CommandName = "CancelRow") Then Dim ID As String = arguments(0) myconnection.Open() Using mycommand As SqlCommand = myconnection.CreateCommand mycommand.CommandText = "delete from ongoing_trips where id=" + ID mycommand.ExecuteNonQuery() End Using myconnection.Close() Response.Redirect("mytrip.aspx") 'Response.Write("<script language='javascript'> alert(" + ID + "); </script>") ElseIf (e.CommandName = "EndRow") Then Dim rid As String = arguments(2) Dim tripIDtaking As String = arguments(1) Dim uid As String = "" Dim uname As String = "" Dim fname As String = "" Dim lname As String = "" Dim tid As String = "" Dim status As String = "" Dim stptname As String = "" Dim edptname As String = "" Dim gdate As String = "" Dim stime As String = "" Dim etime As String = "" Dim nop As String = "" Dim uty As String = "" Dim cfname As String = "" Dim cid As String = "" Dim recur As Char = "" Using con As New SqlConnection(connString) Using cmd As New SqlCommand("SELECT * FROM ongoing_trips inner JOIN accounts ON ongoing_trips.reqid=accounts.userid inner join trips on ongoing_trips.tripidtaking=trips.tripid where (ongoing_trips.status='ACTIVE' AND ongoing_trips.reqid='" + rid + "') and ongoing_trips.tripidtaking='" + tripIDtaking + "'") cmd.Connection = con con.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() While reader.Read() uid = Convert.ToString(reader("userid").ToString()) uname = Convert.ToString(reader("uname").ToString()) fname = Convert.ToString(reader("fname").ToString()) lname = Convert.ToString(reader("lname").ToString()) tid = Convert.ToString(reader("tripid").ToString()) stptname = Convert.ToString(reader("startptname").ToString()) edptname = Convert.ToString(reader("endptname").ToString()) gdate = Convert.ToString(reader("givendate").ToString()) stime = Convert.ToString(reader("starttime").ToString()) etime = Convert.ToString(reader("endtime").ToString()) nop = Convert.ToString(reader("numperson").ToString()) uty = Convert.ToString(reader("usertype").ToString()) recur = Convert.ToString(reader("recurring").ToString()) cfname = Convert.ToString(reader("cfname").ToString()) cid = Convert.ToString(reader("cid").ToString()) End While con.Close() End Using End Using If recur = "Y" Then Response.Write("<script language='javascript'> alert('y'); </script>") ElseIf recur = "N" Then Using con2 As New SqlConnection(connString2) con2.Open() Using mycommand As SqlCommand = con2.CreateCommand mycommand.CommandText = "insert into trips_history values (#userid, #uname, #fname, #lname, #tripid, 'COMPLETED', #startptname, #endptname, #givendate, #starttime, #endtime, #numperson, #usertype, SYSDATETIME(), #cfname, #cid)" mycommand.Parameters.AddWithValue("#userid", uid) mycommand.Parameters.AddWithValue("#uname", uname) mycommand.Parameters.AddWithValue("#fname", fname) mycommand.Parameters.AddWithValue("#lname", lname) mycommand.Parameters.AddWithValue("#tripid", tid) mycommand.Parameters.AddWithValue("#startptname", stptname) mycommand.Parameters.AddWithValue("#endptname", edptname) mycommand.Parameters.AddWithValue("#givendate", gdate) mycommand.Parameters.AddWithValue("#starttime", stime) mycommand.Parameters.AddWithValue("#endtime", etime) mycommand.Parameters.AddWithValue("#numperson", nop) mycommand.Parameters.AddWithValue("#usertype", uty) mycommand.Parameters.AddWithValue("#cfname", cfname) mycommand.Parameters.AddWithValue("#cid", cid) mycommand.ExecuteNonQuery() End Using con2.Close() End Using myconnection.Open() Using mycommand As SqlCommand = myconnection.CreateCommand mycommand.CommandText = "delete from ongoing_trips where tripidtaking=" + tripIDtaking mycommand.ExecuteNonQuery() End Using myconnection.Close() Response.Redirect("myhistory.aspx") End If End If End Sub I not sure why this error happen upon loading of the page i got this error
VB.NET Form1_Load and Button_Click keeps throwing Nullreference Error
Not extremely experienced with Windows Forms applications (this is the first I am trying to build) but I just can't figure out while my app keeps throwing nullreference errors on Form1_Load and 2 of the 7 Browsebutton_Click Subs. The other 5 work perfectly. Additional info: The non-working buttons I added later to my application Both on Form1_Load and clicking the 2 non-working Browse-button return the same errors: System.NullreferenceException: "Object reference not set to an instance of an object" When testing the app in VS everything works totally fine, however after I build the solution, install it and run it on my computer the errors appear AppConfig file appsettings-part looks like this (verfied all the paths and they do exist): <appSettings> <add key="LastZHRverzamelPDF" value="C:\x\pdf files\TestPDF.pdf" /> <add key="LastMapSplitted" value="C:\x\pdf files\ZHRFORMS" /> <add key="LastPersFile" value="C:\x\pdf files\Personeelslijst.xlsx" /> <add key="LastMap1" value="C:\x\pdf files\Salarisslips" /> <add key="LastMap2" value="C:\x\pdf files\Vakantie-uren" /> <add key="LastMap3" value="C:\x\pdf files\ZHRFORMS" /> <add key="LastMap4" value="C:\x\pdf files\Logitime" /> <add key="ClientSettingsProvider.ServiceUri" value="" /> </appSettings> Form1_Load procedure contains the folliwing code: Private Sub Form1_Load(sender As System.Object, e As EventArgs) Handles MyBase.Load Try 'Laatstgekozen waarden uit app.config halen en in lbls neerzetten lblZHRFile.Text = ConfigurationManager.AppSettings("LastZHRverzamelPDF").ToString() lblMapSplitted.Text = ConfigurationManager.AppSettings("LastMapSplitted").ToString() & "\" lblPersFile.Text = ConfigurationManager.AppSettings("LastPersFile").ToString() lblMap1.Text = ConfigurationManager.AppSettings("LastMap1").ToString() & "\" lblMap2.Text = ConfigurationManager.AppSettings("LastMap2").ToString() & "\" lblMap3.Text = ConfigurationManager.AppSettings("LastMap3").ToString() & "\" lblMap4.Text = ConfigurationManager.AppSettings("LastMap4").ToString() & "\" Catch ex As Exception Dim exMsg As String = "Message: " & ex.Message & vbCrLf & "Source: " & ex.Source & vbCrLf & "StackTrace: " & ex.StackTrace MsgBox(exMsg, MsgBoxStyle.Information, "Sub Form1_Load") Dim errormsg As String = ex.Message End Try End Sub I'm loading the appconfig values into the UserForm-labels here to display the last chosen values. Next to the 7 labels I have 7 Browse-buttons to modify the paths. The 2 of them that don't work contain the following code: Private Sub btnZHRPath_Click(sender As Object, e As EventArgs) Handles btnZHRPath.Click Try Dim fd As OpenFileDialog = New OpenFileDialog() fd.FileName = ConfigurationManager.AppSettings("LastZHRverzamelPDF").ToString() Dim strFileName As String With fd .Title = "Selecteer verzamel-PDF file ZHRFORMS uit SAP" .InitialDirectory = "" .Filter = "All files (*.pdf)|*.pdf|All files (*.pdf)|*.pdf" .FilterIndex = 2 .RestoreDirectory = True End With If fd.ShowDialog() = DialogResult.OK Then strFileName = fd.FileName lblZHRFile.Text = strFileName Dim objConfig As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) objConfig.AppSettings.Settings("LastZHRverzamelPDF").Value = strFileName objConfig.Save(ConfigurationSaveMode.Modified) ConfigurationManager.RefreshSection("appSettings") Else lblZHRFile.Text = "(overslaan)" End If Catch ex As Exception Dim exMsg As String = "Message: " & ex.Message & vbCrLf & "Source: " & ex.Source & vbCrLf & "StackTrace: " & ex.StackTrace MsgBox(exMsg, MsgBoxStyle.Information, "btnZHRPath_Click") End Try End Sub Also not working for the same reason: Private Sub btnSplittedPath_Click(sender As Object, e As EventArgs) Handles btnSplittedPath.Click Try If sender = Nothing Then MsgBox("nullsender") lblMapSplitted.Text = "C:\" 'ConfigurationManager.AppSettings("LastMapSplitted").ToString() & "\" Dim Map As FolderBrowserDialog = New FolderBrowserDialog Map.SelectedPath = ConfigurationManager.AppSettings("LastMapSplitted").ToString() Map.Description = "Selecteer doelmap voor gesplitte PDF-files" Map.ShowNewFolderButton = True Dim DoelMap As String = "" If Map.ShowDialog() = Windows.Forms.DialogResult.OK Then DoelMap = Map.SelectedPath & "\" Dim objConfig As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) objConfig.AppSettings.Settings("LastMapSplitted").Value = Map.SelectedPath objConfig.Save(ConfigurationSaveMode.Modified) ConfigurationManager.RefreshSection("appSettings") Else DoelMap = "(overslaan)" End If lblMapSplitted.Text = DoelMap Catch ex As Exception Dim exMsg As String = "Message: " & ex.Message & vbCrLf & "Source: " & ex.Source & vbCrLf & "StackTrace: " & ex.StackTrace MsgBox(exMsg, MsgBoxStyle.Information, "btnSplittedPath_Click") End Try End Sub Strange enough this Browse-button does work correctly (like the remaining 4 with similar code): Private Sub btnFilePath_Click(sender As Object, e As EventArgs) Handles btnFilePath.Click Dim fd As OpenFileDialog = New OpenFileDialog() Dim strFileName As String fd.FileName = ConfigurationManager.AppSettings("LastPersFile").ToString() With fd .Title = "Selecteer bestand met medewerkergegevens" .InitialDirectory = "" .Filter = "All files (*.xl*)|*.xl*|All files (*.xl*)|*.xl*" .FilterIndex = 2 .RestoreDirectory = True End With If fd.ShowDialog() = DialogResult.OK Then strFileName = fd.FileName lblPersFile.Text = strFileName Dim objConfig As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) objConfig.AppSettings.Settings("LastPersFile").Value = strFileName objConfig.Save(ConfigurationSaveMode.Modified) ConfigurationManager.RefreshSection("appSettings") End If End Sub Tried everything to fix this but simply can't figure out why my app keeps throwing these errors at me!! Please help me out here!
Splitting Xml Document according to node
My xml document looks like .. (its actually a kml file for google map..) <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> <Folder> <Name>Folder1</Name> <Placemark> <Name>Placemark1Folder1</Name> <LookAt> <longitude>-122.0839597145766</longitude> <latitude>37.42222904525232</latitude> </LookAt> </Placemark> <Placemark> <Name>Placemark2Folder1</Name> <LookAt> <longitude>-101.083959</longitude> <latitude>26.422</latitude> </LookAt> </Placemark> </Folder> <Folder> <Name>Folder2</Name> <Placemark> <Name>Placemark1Folder2</Name> <LookAt> <longitude>-96.566556</longitude> <latitude>14.422</latitude> </LookAt> </Placemark> </Folder> </Document> </kml> According to each Placemark for each folder node i will like to make a separate xml file like 1st XML: <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> <Folder> <Name>Folder1</Name> <Placemark> <Name>Placemark1Folder1</Name> <LookAt> <longitude>-122.0839597145766</longitude> <latitude>37.42222904525232</latitude> </LookAt> </Placemark> </Folder> </Document> </kml> 2nd xml <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> <Folder> <Name>Folder1</Name> <Placemark> <Name>Placemark2Folder1</Name> <LookAt> <longitude>-101.083959</longitude> <latitude>26.422</latitude> </LookAt> </Placemark> </Folder> </Document> </kml> 3rd xml <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> <Folder> <Name>Folder2</Name> <Placemark> <Name>Placemark1Folder2</Name> <LookAt> <longitude>-96.566556</longitude> <latitude>14.422</latitude> </LookAt> </Placemark> </Folder> </Document> </kml> ..i am very beginner in xml ..help please
Between <Placemark> and </Placemark> tag .. dim strXML as string = .... 'place your XML to be splitted here dim x as integer Dim aXML As New List(Of String) dim sAdd1 as String = '<kml xmlns="http://www.opengis.net/kml/2.2"><Document><Folder> <Name>Folder1</Name><Placemark>' dim sAdd2 as String = '</Placemark></Folder></Document></kml>' while true x=instr(strXML,"<Placemark>") if x > 0 then strXML = mid(strXML,x+11) x=instr(strXML,"</Placemark>") aXML.Add(sAdd1 & mid(strXML,1,x-1) & sAdd2) strXML = mid(strXML,x+12) strXML = trim(strXML) if strXML.length=0 then exit while else exit while endif loop aXML is result array .. The code not tested yet .. so, let me know if that's not working ..
Finally i made success for splitting xml according to node ..I have saved individual kml files according to node in xml ..Here is my solution Public Sub SplitXml(ByVal XmlDoc As XmlDocument, ByVal SaveLocation As String) Dim TmpXml As XmlDocument = XmlDoc Dim Str As String = "<?xml version=""1.0"" encoding=""UTF-8""?>" & "<kml xmlns=" & Chr(34) & "http://www.opengis.net/kml/2.2" & Chr(34) & ">" & "<Document>" Dim DocumentNodes As XmlNodeList = TmpXml.GetElementsByTagName("Document") '======================= 'Building Common String '======================= For Each node As XmlNode In DocumentNodes Dim DocumentChildNodes As XmlNodeList = node.ChildNodes For Each Childnode As XmlNode In DocumentChildNodes If Childnode.Name <> "Folder" Then Str = Str & Childnode.OuterXml.Replace("xmlns=""http://www.opengis.net/kml/2.2""", "") Else Exit For End If Next Next Dim FolderNodes As XmlNodeList = TmpXml.GetElementsByTagName("Folder") Dim FolderName As String = String.Empty Dim XmlDocSave As XmlDocument = New XmlDocument() Dim StrXml As String = String.Empty Dim TmpStr As String = String.Empty Dim FileName As String = String.Empty For Each node As XmlNode In FolderNodes '============================================================== 'Creating Directories For kml Getting Name from FirstChild Node '=============================================================== FolderName = DirectCast(DirectCast(node, System.Xml.XmlElement).FirstChild, System.Xml.XmlElement).InnerText FolderName = FolderName.Replace(".", "_") FolderName = FolderName.Replace(" ", "") If (Not System.IO.Directory.Exists(SaveLocation & "\" & FolderName)) Then System.IO.Directory.CreateDirectory(SaveLocation & "\" & FolderName) End If '============================================================== 'Creating kml Files Getting Name from FirstChild Node '=============================================================== Dim FolderChildNodes As XmlNodeList = node.ChildNodes For Each childnode As XmlNode In FolderChildNodes If childnode.Name = "Placemark" Then FileName = DirectCast(DirectCast(childnode, System.Xml.XmlElement).FirstChild, System.Xml.XmlElement).InnerText FileName = FileName.Replace(".", "_") FileName = FileName.Replace(" ", "") StrXml = Str & "<Folder>" & TmpStr & childnode.OuterXml & "</Folder>" & "</Document>" & "</kml>" XmlDocSave.LoadXml(StrXml) XmlDocSave.Save(SaveLocation & "\" & FolderName & "\" & FileName & ".kml") XmlDocSave = New XmlDocument() StrXml = String.Empty Else TmpStr = TmpStr & childnode.OuterXml End If Next TmpStr = String.Empty Next End Sub
How to add the textbox name as parameter in a sub
I have created a button to add the fields in a a textbox and I wanted to pass the textbox name as parameter in a sub,which inturn inserts into the database..How can i do it..pls find my code for reference below in vb.net The code for inserting the values in database Sub Add_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click Dim addedButton As Button = sender Dim sqlcmd As SqlCommand Dim insertdata As String addedButton.Text = "Added" adduser = True addedButton.Enabled = True If (cname.Value = " " Or cid.Value = " " Or cadd.Value = " " Or cph.Value = " " Or fax.Value = " " Or cmail.Value = " ") Then Message.InnerHtml = "ERROR: Null values not allowed for " _ & "Client ID, Name" Message.Style("color") = "red" BindGrid() Else Message.InnerHtml = "<b>Client Record has been added</b><br/>" End If insertdata = "INSERT INTO dbo.ClientInfo([Client Name],[Client ID],[Client Address],[Client Telephone No],[Client Fax No],[Client E-mail]) values(" insertdata = insertdata + " ' " + cname.Value + " '," + cid.Value + ",' " + cadd.Value + " '," + cph.Value + "," + fax.Value + "," + cmail.Value sqlcmd = New SqlCommand(insertdata, sqlcon) Try sqlcmd.Connection.Open() Dim addcount As Integer = sqlcmd.ExecuteNonQuery() If addcount > 0 Then Message.InnerHtml = "Record successfully Added" Else Message.InnerHtml = "Record not added" End If Catch ex As SqlException If ex.Number = 2627 Then Message.InnerHtml = "ERROR: A record already exists with " _ & "the same primary key" End If Finally sqlcmd.Connection.Close() BindGrid() End Try End Sub <asp:Button id="Button1" Text="Add data" OnClick="Add_Click" runat="server"/><br /> Name:<input type ="text" id="cname" name="" value="" runat="server"/><br /> ID: <input type = "text" id="cid" name="txtclientid" value="" runat="server"/><br /> Address:<input type="text" id="cadd" name="txtclientadd" value="" runat="server"/><br /> Phone No:<input type="text" id="cph" name="txtno" value="" runat="server" /><br /> Fax No:<input type="text" id="fax" name="faxno" value="" runat="server"/><br /> E-mail:<input type="text" id="cmail" name="mail" value="" runat="server"/><br /> <input type="reset" name="reset" value="Clear" /><br />
Not exactly what you asked for, but closer to what you should be doing: Public Sub InsertClientInfo(ByVal ClientName As String, ByVal ClientID As Integer, ByVal ClientAddress As String, ByVal ClientPhone As String, ByVal ClientFax As String, ByVal ClientEmail As String) Dim sql As String = _ "INSERT INTO ClientInfo (" & _ "[Client Name],[Client ID],[Client Address],[Client Telephone No],[Client Fax No],[Client E-mail]" & _ ") VALUES (" & _ "#ClientName, #ClientID, #ClientAddress, #ClientPhone, #ClientFax, #ClientEmail)" Using cn As New SqlConnection("connection string"), _ cmd As New SqlCommand(sql, cn) 'I had to guess at the column types and lengths here. Adjust accordingly cmd.Parameters.Add("#ClientName", SqlDbType.NVarChar, 50).Value = ClientName cmd.Parameters.Add("#ClientID", SqlDbType.Int).Value = ClientID cmd.Parameters.Add("#ClientAddress", SqlDbType.NVarChar, 200).Value = ClientAddress cmd.Parameters.Add("#ClientPhone", SqlDbType.NVarChar, 16).Value = ClientPhone cmd.Parameters.Add("#ClientFax", SqlDbType.NVarChar, 16).Value = ClientFax cmd.Parameters.Add("#ClientEmail", SqlDbType.NVarChar, 50).Value = ClientEmail cn.Open() cmd.ExecuteNonQuery() End Using End Sub Note that I had to guess at data types and sizes. You need to fix that to make your actual table definitions. Call it like this: InsertClientInfo(textname.Text, Convert.ToInt32(textclientid.Text), txtclientadd.Text, txtno.Text, faxno.Text, mail.Text)
To pass the TEXTBOX name to any sub do as follows, Sub SomeSubName(ThisTextboxName as string) 'your code here End Sub or to a function Function SomeFunctionName(ThisTextBoxName as String) As Boolean 'your code here End Function Where... SomeSubName and SomeFunctionName are the names of your sub or function ThisTextBoxName is the variable name of the STRING data which is the actual textbox name So if your textbox is named txtPhone Then you would pass it as.... SomeSubName(txtPhone.Name) or Dim Test as Boolean Test = SomeFunctionName(txtPhone.Name)