none
equivalent of vb 6 string RRS feed

  • Question

  • Is there a better way of declaring the string object below.  In the old VB6.0 you could write string(10," ") & string(20," ") etc
    The way I now do this is to declare a new variable for every repeating sequence.  This is not very elegant.
            Dim s2 As New String(" "c, 10), s3 As New String(" "c, 20), s4 As New String(" "c, 4), s5 As New String(" "c, 5)
           strRanking = strRanking & vbCrLf & s2 & "Name" & s3 & "Rank" & s4 & "Points" & s5 & "Court"
           
    In my project I might have to declare 10 different strings.

    BraafPaard

    Thursday, December 1, 2016 12:53 AM

Answers

  • If you try this declaration without the New keyword it does not work.  It will not accept the 10. With the New keyword you get 3 options on how to define the string.

    I don't know who you are replying to, but if you are saying that the requirement to use 'New' means that you have to create a variable, that's not so.

    strRanking = strRanking & vbCrLf & New String(" ", 10) & "Name" & New String(" ", 20)
    but that's more complicated than just using Space().
    • Marked as answer by BraafPaard Saturday, December 3, 2016 10:55 PM
    Thursday, December 1, 2016 8:00 PM

All replies

  • This Visual Basic is not VB6 and has not been for over a decade.

    If you want to contact Microsoft about how things were performed back in antique days of VB6 compared to how they are performed nowadays in VB.Net then this would not be the forum for that.

    New keyword is not required for instantiating a string. Once a string is instantiated it can be repeatedly used without having to instantiate it again for example if it is instantiated globally. It can be set to = "" or = string.empty. &= can be used with a string to append to the end of the string.

    String Data Type (Visual Basic)

    Yes in your project you may have to declare 10 different strings as you don't seem to know how to use strings in VB.Net and for some reason then believe some major difference between VB6 and VB.Net regarding strings is accurate for some reason. But probably because you haven't learned enough to use VB.Net and instead rely on VB6 for some reason trying to make a way via VB.Net.

    Also see Strings in Visual Basic.


    La vida loca

    Thursday, December 1, 2016 1:09 AM
  • In the old VB6.0 you could write string(10," ") & string(20," ") etc

    If you are transitioning from VB 6 to VB .NET you might find this guide helpful:

    https://en.wikibooks.org/wiki/Visual_Basic_.NET/Visual_Basic_6_to_.NET_Function_Equivalents

    - Wayne

    Thursday, December 1, 2016 4:10 AM
  • Is there a better way of declaring the string object below.  In the old VB6.0 you could write string(10," ") & string(20," ") etc

    The .Net equivalent of 'string(10," ")' is 'Space(10)'.  There is no need to create variables. See:
    https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.space(v=vs.110).aspx

    Thursday, December 1, 2016 4:34 AM
  • You could just make a VB.NET function with logic that returns the final results.

    https://www.tutorialspoint.com/vb.net/vb.net_functions.htm

    Thursday, December 1, 2016 6:26 AM
  • Dim s2 As New String(" "c, 10) is part of the Visual Basic 2010 syntax I thought.    It repeats " " 10 times and is equivalent to space(10).  If you try this declaration without the New keyword it does not work.  It will not accept the 10. With the New keyword you get 3 options on how to define the string.

    Of course you know all of this so I don't fully understand the scorn.

    Thanks anyway.


    BraafPaard

    Thursday, December 1, 2016 5:47 PM
  • Yes.  I should have repeated something else for this question.  maybe

    Dim s2 As New String("P"c, 10)

    Thanks for your reply.


    BraafPaard

    Thursday, December 1, 2016 5:50 PM
  • If you try this declaration without the New keyword it does not work.  It will not accept the 10. With the New keyword you get 3 options on how to define the string.

    I don't know who you are replying to, but if you are saying that the requirement to use 'New' means that you have to create a variable, that's not so.

    strRanking = strRanking & vbCrLf & New String(" ", 10) & "Name" & New String(" ", 20)
    but that's more complicated than just using Space().
    • Marked as answer by BraafPaard Saturday, December 3, 2016 10:55 PM
    Thursday, December 1, 2016 8:00 PM
  • maybe

    Dim s2 As New String("P"c, 10)

    Perhaps this is what you mean: https://msdn.microsoft.com/en-us/library/w37th3kf(v=vs.90).aspx

    Thursday, December 1, 2016 9:18 PM
  • Hi DecentHorse, 

    It is not the question if there is a better way of declaring a string of spaces.

    The question is if declaring a string of spaces is still from today's development. 

    It comes from the punched card where areas were created which had always the same size and printing was always done with non proportional characters. 

    Maybe you should stop using that as template for your development. 



    Success
    Cor






    Friday, December 2, 2016 8:17 AM
  • Hello,

    As indicated already, things have changed since VB6 and for the better yet I can understand how coming from a VB6 background may very well make one dislike the new ways of coding, be it strings or another things such as working with databases.

    Generally speaking there is more code needed in VB.NET (or C#) than in VB6. When one looks at the possibilities with VB6 to VB.NET they both can do amazing things but when you want to get down and dirty with coding there is truly no comparision between the two, VB.NET (and C#) are by far a more advance way to write solutions.

    Given your question, with VB.NET we can write our own function and hide the implementation of creating our string. This is no different than using native functions in VB6 or VB.NET (or C#) yet the big difference is in native functions we have no clue how many lines of code Microsoft wrote to create said functions so that means why not the developer write their own functions.

    When writing such functions as this one and you have other projects that you would use them in, create a class project that can be used independent of any one project. To use these functions compile it to a common folder that when needed you add a reference to the current project and Visual Studio copies the DLL to your project folder.

    One consideration for a function, the arguments are done this way as to match up with language extension methods

        ''' <summary>
        ''' Create a new string with options
        ''' </summary>
        ''' <param name="sender">First char is used for repeating</param>
        ''' <param name="amount">how many times to repeat the char in sender</param>
        ''' <returns>a new string</returns>
        Public Function Repeat(ByVal sender As String, Optional ByVal amount As Integer = 1) As String
            Return New String(Convert.ToChar(sender), amount)
        End Function
    Dim Value As String = Repeat(" ", 10)
    Console.WriteLine($"'{Value}'")
    
    Value = Repeat("P", 3)
    Console.WriteLine($"'{Value}'")
    
    Value = Repeat("x")
    Console.WriteLine($"'{Value}'")
    Dim Name As String = "Karen"
    Dim result As String = String.Concat(Repeat("_", 10), vbCrLf, Repeat("-", 20), $"Hello {Name}", Repeat(".", 5))
    Console.WriteLine(result)

    You might wonder why I used a string for the first argument, whatever we can do to make things easier (as what you are looking for) do it, there are zero issues.

    I mentioned language extensions, they are great for reuse and hiding implementation. They begin as a function or procedure then are declared so that are used method based rather than conventional function or procedures.

    Public Module Extensions
        <DebuggerStepThrough()>
        <Runtime.CompilerServices.Extension()>
        Public Function ToInteger(ByVal sender As String) As Integer
            Dim holder As Integer = 0
            If Integer.TryParse(sender, holder) Then
                Return holder
            Else
                Return -1
            End If
        End Function
    End Module
    In the end it's all about the developer's perspective. Similar points can be with say VB.NET/C# moving to JavaScript coding e.g. rather than writing simply code more likely than not that has changed but we can make things easy e.g. jQuery extend or prototypes. The big shift for some is there more or less are no types as know in .NET.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Friday, December 2, 2016 11:09 AM
    Moderator
  • Hi DecentHorse, 

    It is not the question if there is a better way of declaring a string of spaces.

    The question is if declaring a string of spaces is still from today's development. 

    It comes from the punched card where areas were created which had always the same size and printing was always done with non proportional characters. 

    Maybe you should stop using that as template for your development. 



    Success
    Cor

    I wish you would stop being presumptive and critical of others work.  There are legitimate reasons to create strings that repeat characters today.  I often use it in debugging as 'markers' so I can scan debug output and find some particular part.  Like this,

            Debug.WriteLine(New String("-"c, 20))

    Your response did not address the OP's question in any way.  You could have asked the OP why they wanted to do this and then addressed that.


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it." - MSDN User JohnWein    Multics - An OS ahead of its time.

    Friday, December 2, 2016 12:04 PM
  • I was replying that in the declaration of string I had to use New.  This was a response to a person  who said you did not need to use New.

    I did not know you can use New String like you showed.  That really answers my question!  No need to declare a variable.

    Thanks


    BraafPaard

    Friday, December 2, 2016 1:30 PM
  • Thanks for your reply.  I learned a lot.  I am  interested in your advise to create a common folder for functions to be reused in all projects.  How to do this?  I already have one  function that I use everywhere (adding items with there ID to a listbox)

    Do I create a new project and then add each function as a separate class and then compile the new project?

    ( I am sorry to ask but is compile the same as build?). 


    BraafPaard

    Friday, December 2, 2016 1:43 PM
  • Okay I'm going to toss a good deal your way but know up front all the code is clean, well done and easy to read.

    The project is downloadable from Microsoft OneDrive

    https://1drv.ms/u/s!AtGAgKKpqdWjiAy-zSjP1rMjNyqY

    Screenshot of solution, those in yellow can be compile and used in other solutions by adding one or more to another project outside of this solution via project references add.

    There are sparse notes/comments that are important to read as you come across them especially in the class projects.

    For this sample I read data from a local SQL-Server database and I included a SQL script to generate the database and all data in the solution under the MasterDetailDataOperation project. Note that there is a line of code in Operations.vb that indicates KARENS-PC for the SQL Server name, that needs to change to match your server name.

    Main focuses

    • Writing clean modular and reusable code.
    • Separating data operations from UI.
    • Use of language extension methods

    If getting the data side setup then simply examine the code as there are many things that need to be considered to get the database setup if you don't have SQL-Server express installed.

    Okay here is a screenshot of the demo app.

    Not much code in the form

    Imports BindingSourceExtensions
    Imports MasterDetailDataOperations
    
    Public Class Form1
        ''' <summary>
        ''' Containers for our customer and orders data
        ''' which are setup in Operations class.
        ''' </summary>
        WithEvents bsMaster As New BindingSource()
        WithEvents bsDetails As New BindingSource()
        Private StateInformation As List(Of StateItems)
        ''' <summary>
        ''' Load data using the class library MasterDetailsOperations
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim ops As New Operations
            ops.LoadData()
            If Not ops.HasErrors Then
                StateInformation = ops.StateInformation
                bsMaster = ops.Master
                bsDetails = ops.Details
                DataGridView1.DataSource = bsMaster
                DataGridView2.DataSource = bsDetails
                BindingNavigator1.BindingSource = bsMaster
            Else
                MessageBox.Show(ops.ExceptionMessage)
            End If
        End Sub
        ''' <summary>
        ''' Example for obtaining current order id and it's parent record id via extension method
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Sub cmdCurrentOrder_Click(sender As Object, e As EventArgs) Handles cmdCurrentOrder.Click
            MessageBox.Show($"Current order id {bsDetails.CurrentOrderIdentifier} current customer {bsDetails.CurrentOrderCustomerIdentifier}")
        End Sub
        ''' <summary>
        ''' Example for obtaining current customer row id via extension method
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Sub cmdCurrentCustomer_Click(sender As Object, e As EventArgs) Handles cmdCurrentCustomer.Click
            MessageBox.Show($"Customer key {bsMaster.CurrentCustomerIdentifier}")
        End Sub
        ''' <summary>
        ''' Example of a string extension
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Sub cmdProperCase_Click(sender As Object, e As EventArgs) Handles cmdProperCase.Click
            Dim sb As New Text.StringBuilder
            Dim People As New List(Of Person) From
                {
                    New Person With {.FirstName = "karen", .LastName = "PAYNE"},
                    New Person With {.FirstName = "jIm", .LastName = "aDams"}
                }
    
            People.ForEach(Sub(person)
                               sb.AppendLine(person.FullName)
                           End Sub)
    
            MessageBox.Show(sb.ToString)
        End Sub
    End Class
    

    Data operations are in a class project which makes use of yet another class project.

    Imports System.Data.SqlClient
    Imports System.Windows.Forms
    
    '
    ' This is a project within the solution I created
    '
    Imports DataExtensions
    
    Public Class Operations
        ''' <summary>
        ''' Connection string to SQL-Server database
        ''' </summary>
        ''' <remarks>
        ''' See script instructions
        ''' CreateDatabaseAndData.sql
        ''' </remarks>
        Private ConnectionString As String = "Data Source=KARENS-PC;Initial Catalog=MasterDetailSimple;Integrated Security=True"
        Public Property HasErrors As Boolean
        Public Property ExceptionMessage As String
        ''' <summary>
        ''' This is the master data
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property Master As New BindingSource
        ''' <summary>
        ''' This is the details to the Master 
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Property Details As New BindingSource
        Public Property StateInformation As List(Of StateItems)
        Public Sub New()
            GetStateInformation()
        End Sub
        ''' <summary>
        ''' Read state table data into a list
        ''' </summary>
        Private Sub GetStateInformation()
            StateInformation = New List(Of StateItems)
            StateInformation.Add(New StateItems With {.Identifier = -1, .Name = "Select one"})
            Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
                Using cmd As New SqlCommand With {.Connection = cn, .CommandText = "SELECT id,StateName,StateAbbrev FROM StateLookup"}
                    cn.Open()
                    Dim reader As SqlDataReader = cmd.ExecuteReader
                    While reader.Read
                        StateInformation.Add(New StateItems With {.Identifier = reader.GetInt32(0), .Name = reader.GetString(1), .Abbreviation = reader.GetString(2)})
                    End While
                End Using
            End Using
        End Sub
        ''' <summary>
        ''' Initial data loaded was generated by Red Gate SQL Data Generator
        ''' so the invoice numbers will be different than the ones created
        ''' here with the database sequence I have provided here.
        ''' </summary>
        Public Sub LoadData()
            Dim ds As New DataSet
            Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
                Dim da As New SqlDataAdapter("SELECT id,FirstName,LastName,Address,City,State,ZipCode FROM Customer", cn)
                Try
                    da.Fill(ds, "Customer")
                    da = New SqlDataAdapter("SELECT id,CustomerId,OrderDate,Invoice FROM Orders", cn)
                    da.Fill(ds, "Orders")
                    ds.SetRelation("Customer", "Orders", "Id", "CustomerId")
    
                    Master.DataSource = ds
                    Master.DataMember = ds.Tables(0).TableName
    
                    Details.DataSource = Master
                    Details.DataMember = ds.Relations(0).RelationName
    
                    Dim CustomerTable As DataTable = ds.Tables("Customer")
                    CustomerTable.Columns("id").ColumnMapping = MappingType.Hidden
                    Dim OrderTable As DataTable = ds.Tables("Orders")
                    OrderTable.Columns("id").ColumnMapping = MappingType.Hidden
                    OrderTable.Columns("CustomerId").ColumnMapping = MappingType.Hidden
                Catch ex As Exception
                    HasErrors = True
                    ExceptionMessage = ex.Message
                End Try
            End Using
        End Sub
    
    End Class
    
    All code was taken from pre-written solution and several projects I had hanging around so much of putting this together was copy and paste.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, December 2, 2016 3:17 PM
    Moderator
  • Thanks for all the time you spent on educating us hackers.  I could not use your software . Got the message that my version of Visual Basic 2010 is not compatible with the software.

    In the meantime I have figured out (with internet help) how to make a commonFunction.dll file.  I added it to one of my projects and it works.  Wonderful.

    Thanks again for your help.


    BraafPaard

    Saturday, December 3, 2016 2:22 PM