Writeline to textbox? - vb.net

Stupid question here, but here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As DataTable
dt = CType(dgrGrid.DataSource, DataTable).Copy
Dim drs() As DataRow = dt.Select("CustomerID = 222")
For Each row As DataRow In drs
For Each item As Object In row.ItemArray
Debug.WriteLine("{0}", item)
Next
Next
End Sub
I can see in the debug window all my values.
Now if I need to spit out this value to a textbox, I am not sure how to do it.
The goal is to keep using itemArray to get the value.

You can use something like this:
Dim rows = dt.Select() ' Or select using a criteria like you did
Me.TextBox1.Text = String.Join(Environment.NewLine, _
rows.Select(Function(r) String.Join(",", r.ItemArray)))
The TextBox1 should be MultiLine to show Environment.NewLine.
Also if you are looking for something like AppendLine, use:
Me.TextBox1.AppendText("something" & Environment.NewLine)

In addition to Reza's answer, and if you're lazy like me and don't want to write Environment.NewLine everywhere, you can create an extension method for adding new lines:
Imports System.Runtime.CompilerServices
Public Module Extensions
<Extension()> _
Public Sub AppendLine(ByVal TargetTextBox As TextBox, ByVal Text As String)
TargetTextBox.AppendText(Text & Environment.NewLine)
End Sub
End Module
Usage:
For Each item As Object In row.ItemArray
TextBox1.AppendLine(item.ToString())
Next

Related

VB.NET DataSet table data empty

I'm trying to use the dataset for a report, but the data is gone when I try to use it. Here is my code for the most part:
Variables:
Dim ResultsDataView As DataView
Dim ResultsDataSet As New DataSet
Dim ResultsTable As New DataTable
Dim SQLQuery As String
Search:
This is where a datagrid is populated in the main view. The data shows up perfectly.
Private Sub Search(Optional ByVal Bind As Boolean = True, Optional ByVal SearchType As String = "", Optional ByVal SearchButton As String = "")
Dim SQLQuery As String
Dim ResultsDataSet
Dim LabelText As String
Dim MultiBudgetCenter As Integer = 0
SQLQuery = "A long and detailed SQL query that grabs N rows with 7 columns"
ResultsDataSet = RunQuery(SQLQuery)
ResultsTable = ResultsDataSet.Tables(0)
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
sb.Append(item.ToString + ","c)
Response.Write(item.ToString + "\n")
Response.Write(vbNewLine)
Next
sb.Append(vbCr & vbLf)
Next
'Response.End()
If Bind Then
BindData(ResultsDataSet)
End If
End Sub
Binding Data:
I think this is a cause in the issue.
Private Sub BindData(ByVal InputDataSet As DataSet)
ResultsDataView = InputDataSet.Tables("Results").DefaultView
ResultsDataView.Sort = ViewState("SortExpression").ToString()
ResultsGridView.DataSource = ResultsDataView
ResultsGridView.DataBind()
End Sub
Reporting action:
This is where I am trying to use the table data. But it is showing as nothing.
Protected Sub ReportButton_Click(sender As Object, e As EventArgs) Handles ReportButton.Click
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
Response.Write(item.ToString)
Next
Next
End Sub
The reason I'm trying to loop through this data is to both display the data in a gridview on the main view as well as export the data to CSV. If there is a different way to export a SQL query to CSV, I'm open to any suggestions.
There has to be something I can do to get the data from the SQL query to persist through the ReportButton_Click method. I've tried copying the datatable, I've tried global variables, I've tried different methods of looping through the dataset. What am I missing?!
Thank you all in advance.
EDIT
Here is the Page_Load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
'set focus to postback control
Dim x As String = GetPostBackControlName(Page)
If Len(x) > 0 Then
x = x.Replace("$", "_")
SetFocus(x)
End If
End If
If Not IsPostBack Then
ResultsGridView.AllowPaging = False
'Enable Gridview sorting
ResultsGridView.AllowSorting = True
'Initialize the sorting expression
ViewState("SortExpression") = "ID DESC"
'Populate the Gridview
Search()
End If
End Sub
In your search function add this line after the ResultsTable setting
ResultsTable = ResultsDataSet.Tables(0)
Session("LastSearch") = ResultsTable
Then in your report click event handler recover your data from the Session variable
Protected Sub ReportButton_Click(sender As Object, e As EventArgs) Handles ReportButton.Click
ResultsTable = DirectCast(Session("LastSearch"), DataTable)
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
Response.Write(item.ToString)
Next
Next
End Sub
You need to read about ASP.NET Life Cycle and understand that every time ASP.NET calls your methods it creates a new instance of your Page class. Of course this means that global page variables in ASP.NET are not very useful.
Also consider to read about that Session object and not misuse it.
What is the difference between SessionState and ViewState?

How to write a List(of) to a text file and retrieve it (vb.net)

Title. I need to write my ListOf, which just contains values such as Zero, Zero, One, One, Two, etc to a text file, and then load back up again. Any help appreciated!
Hello & Welcome to Stack Overflow!. In the future please show some effort when asking a question and at least google or even bing your question first, there are a stack of tutorials regarding your question.With that being said, I am going to give you a lifeline.From what I can tell, you want to write your list to a text file and then read from that text file.
Module Module1
Dim mylist As List(Of String) = New List(Of String)
Dim desktopPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim newfile As String = "myTextFile.txt"
Dim newPath As String = System.IO.Path.Combine(desktopPath, newfile)
Sub Main()
mylist.Add("Zero")
mylist.Add("One")
mylist.Add("Two")
mylist.Add("Three")
writer()
End Sub
Sub writer()
Using sw As New System.IO.StreamWriter(newPath)
For Each item As String In mylist
sw.WriteLine(item)
Next
sw.Flush() ''yeap I'm the sort of person that flushes it then closes it
sw.Close()
End Using
reader()
End Sub
Sub reader()
Using sr As New System.IO.StreamReader(newPath)
Console.WriteLine(sr.ReadToEnd)
sr.Close()
End Using
Console.ReadKey()
End Sub
End Module
I didn't put too much effort into this, I will leave the rest up to you, however this should get your well and truly on your way.This was done with a Console applicationAlso if you have any problems or even a question or two regarding my answer, leave a comment and I will do my best to answer you and help you out as I know learning something for the first time can be difficult and you will have lots of questions.EDIT: If you need to load each value separately eg skip the first 4 lines and only read the 5th line, you should look into learning how to do a loop.
EDIT - Here is what I think you are trying to achieve just from reading your comments.
''Reads whatever is in the newPath Textfile and addes the words to a listbox or wherever is needed.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
ListBox1.Items.Clear() ''This is stop double ups.
Dim myTextFile = System.IO.File.ReadAllLines(newPath)
For Each word As String In myTextFile
ListBox1.Items.Add(word) '' change this to mylist if need be
''mylist.Add(word)
Next
End Sub
This should fix your problem, although you may need to clear the mylist first or even create another array.
Here's some sandbox code:
Imports System.Xml.Serialization
Imports System.IO
Public Class frmTest
Dim l1 As New List(Of String)
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
l1.AddRange({"1", "b", "7"})
Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(List(Of String)))
' To write to a file, create a StreamWriter object.
Dim myWriter As StreamWriter = New StreamWriter("C:\temp\list.xml")
mySerializer.Serialize(myWriter, l1)
myWriter.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myFileStream As FileStream = New FileStream("C:\temp\list.xml", FileMode.Open)
Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(List(Of String)))
' Call the Deserialize method and cast to the object type.
l1 = New List(Of String) ' refresh for test
l1 = CType(mySerializer.Deserialize(myFileStream), List(Of String))
Stop ' l1 is populated
End Sub
End Class

Calling a procedure from its non native form

Ok, so
frmResult populates a ListView with various calculations
frmMenu has an export button (see code below). Pressing this is supposed to export the data in the ListView to a txt file. Currently, this button does not work. It says, List View is undeclared - obviously because the code shown below is not 'seeing' data held in frmResult
Question – how do I call the procedures stored in frmResult so that frmMenu can 'see' it.
Public Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
Dim fileSaved As Boolean
Dim filePath As String
Do Until fileSaved
'Request filename from user
Dim saveFile As String = InputBox("Enter a file name to save this message")
'Click Cancel to exit saving the work
If saveFile = "" Then Exit Sub
'
Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
filePath = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
'the filePath String contains the path you want to save the file to.
Dim rtb As New RichTextBox
rtb.AppendText("Generation, Num Of Juveniles, Num of Adults, Num of Semiles, Total" & vbNewLine)
For Each saveitem As ListViewItem In ListView1.Items
rtb.AppendText(
saveitem.Text & ", " &
saveitem.SubItems(1).Text & ", " &
saveitem.SubItems(2).Text & ", " &
saveitem.SubItems(3).Text & ", " &
saveitem.SubItems(4).Text & vbNewLine)
Next
rtb.SaveFile(filePath, RichTextBoxStreamType.PlainText)
End Sub
Is this what you mean?
Public Sub Init()
'... (all the code)
End Sub
Private Sub Results_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call Init()
End Sub
You can call Init() from every form load you want. Maybe you want to create a module and store there your methods.
By the way, you only use Function when your methods needs to return a value.
If your code uses elements of the form (or other objects not constant) you need to pass those to the method, like this:
Public Sub Init(myListView As ListView)
myListView.Items.Add("something")
'...
End Sub
Private Sub Results_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call Init(ListView1)
End Sub
You can add as many parameters as you need. You have to learn the basics before going ant further.
This is a great piece of literature for those struggling with the basics like myself.
You can write code to access objects on a different form. However, you must fully identify the name of the object by preceding it with the object variable name.
Dim resultsForm As New frmResults
resultsForm.lblAverage.Text = sngAverage.ToString()
In these statements, for example, I have declared an object variable called resultsForm that is linked to the form frmResults. The second statement assigns the string value of sngAverage to the lblAverage label box on the frmResults form.
In my code, I needed to change the line that said:
For Each saveitem As ListViewItem In ListView1.Items
To this:
For Each saveitem As ListViewItem In Results.ListView1.Items
I also needed to make sure that the procedure on formResults was made Public not Private

creating text file in VB.NET adding extra line

I am trying to create text file with the code below; but there is always an extra line at the end that I cannot get rid of. Is there any way to modify this code to write the text file without the last line?? Help appreciated:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MekdamFile As String
MekdamFile = "C:\TEMP\MEKDAM.txt"
Dim dones As New List(Of String)
For i = 1 To 10
dones.Add("test test " & i)
Next
Using sw As New StreamWriter(MekdamFile)
For Each i As String In dones
sw.WriteLine(i)
Next
End Using
End Sub
End Class
Thanks for help in advance...
StreamWriter.WriteLine always writes a line terminator.
On the last iteration of the loop you could use sw.Write instead.
Your code can be simplified a bit:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
File.WriteAllText("C:\TEMP\MEKDAM.txt", [String].Join( _
Environment.NewLine, _
Enumerable.Range(1, 10).[Select](Function(i) "Test test" + Cstr(i))))
End Sub
You are calling WriteLINE, so whatever you pass into it will be appended with a newline character sequence.
If you don't want to write the newline, use Write instead of WriteLine. Of course, you should then append the newline yourself for all lines except the last.
Alternatively, for a small text, just build the whole text, then trim the end of it and write it at once:
Dim sb As new StringBuilder();
For i = 1 To 10
sb.AppendLine("line " + i);
Next
File.WriteAllText(path, sb.ToString().TrimEnd());

Validate only newly typed text

I'm making simple application. There is a textbox and a ListBox. When user type something in the textbox, that text add to the ListBox split by space after some validation process. I done it. Here is my code.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'split by space
Dim arrText() As String = Split(TextBox1.Text, " ")
ListBox1.Items.Clear()
'ValidateText is a function
For i = 0 To UBound(arrText)
ListBox1.Items.Add(ValidateText(arrText(i)))
Next i
End Sub
But I want to upgrade it because the validation process take more time. When user type something in the textbox need to do the same process but for only newly typed text. (From the cursor position forward to the end of the text) already validated text doesn’t need to validate again. I think someone can help.
Note: user can be also copy & paste words in the textbox
Thank in advance
I have found a solution thanks to lapheal who member in msdn forum
Private validatedDic As New Dictionary(Of String, String) 'or Dictionary(Of String, Object)?
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'split by space
Dim arrText() As String = Split(TextBox3.Text, " ")
ListBox1.Items.Clear()
'ValidateText is a function
For i = 0 To UBound(arrText)
Dim text As String = String.Empty
If Not validatedDic.TryGetValue(arrText(i), text) Then
text = ValidateText(arrText(i))
validatedDic(arrText(i)) = text
End If
ListBox1.Items.Add(text)
Next i
End Sub