StringBuilder Class in VB.NET: Part 2
In this article I will explain you about the StringBuilder Class in VB.NET.
As my you learn StringBuilder class in my previous article. Now in this article we look about the solution in this case is to pass a StringBuilder as the argument in place of a String since a StringBuilder instance can be modified by GetWindowText. Keep in mind that the StringBuilder instance should not exceed the capacity of the StringBuilder. The StringBuilder will be initialized to a fixed length before calling GetWindowText. If you initialize a StringBuilder with a capacity of N, the unmanaged code marshaler uses a buffer of size (N + 1) characters. StringBuilder does not have a null terminator, while the unmanaged string pointer does.
Example given below is the code for passing a StringBuilder instance to the GetWindowText API.
Example of GetWindowText in .NET DLL Import
Public Class Win32API
Public Shared Sub GetWindowText(ByVal handle As IntPtr, ByVal s As StringBuilder, ByVal nMaxCount As Integer)
Public Function GetText(ByVal handle As IntPtr) As [String]
Dim sb As New StringBuilder(256)
GetWindowText(handle, sb, sb.Capacity)
Private Sub TestGetText()
The below given example illustrates StringBuilder usage when building SQL queries. The code segment connects to a Microsoft SQL Server Pubs database, which is installed by default as an example database with predefined options. You'll need to change the SqlClient constructor for use of the example on your computer.
Example of StringBuilder Class
' for ADO.Net
' for SQL
' for FileStream class
' for StringBuilder class
Public Class WriteXML
Public Shared Sub Main()
' Build a connection
Dim myConn As New SqlConnection("server=vesnet27;uid=sa;pwd=;database=Pubs")
' Build the SQL string
Dim mySql As New StringBuilder("SELECT emp_id, fname, lname,hire_date ")
mySql.Append("FROM employee ")
mySql.Append("WHERE lname LIKE 'A%' ")
mySql.Append("ORDER BY lname")
' Build the DataSet Command object
Dim myCmd As New SqlCommand(mySql.ToString(), myConn)
' Build the DataSet
Dim myDs As New DataSet()
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = myCmd
' Fill the DataSet with a dataset table named "Products"
' Get a FileStream object
Dim myFs As New FileStream("myXmlData.xml", FileMode.OpenOrCreate, FileAccess.Write)
' Use the WriteXml method of DataSet object to write an XML file from
' the DataSet
The example above, has this output:
Hope this article would have helped you in understanding the StringBuilder Class in VB.NET.