Home > Net >  .txt file to Rich text box with changes
.txt file to Rich text box with changes

Time:08-27

Im going to try to make this as simple as i possible can. I work in a shipping company, where we email our clients if there is any issues with their orders. I have recently made a vb.net program that standardizes these emails. Now i am rewriting the program so that the templates can be edited from a text file. right now they are hard coded into the program itself.

SO, this is what im wanting to do

Template.txt -> Good afternoon %NAME% your order has shipped.

I want the program to open this text file, Change %NAME% to variable CustName which is entered from a text box, Then show the updated text in a RichTextBox. But i dont want the template.txt to save the changes.

Was wondering if you fine people could help me out with this.

Thanks a lot!

CodePudding user response:

I think the syntax you're looking for is something like

String.Format("Good afternoon {0} your order has shipped", name_variable)

If you wanted to change two pieces of information, you could use

String.Format("Good afternoon {0} your order has {1}", name_variable, "shipped")

CodePudding user response:

The first answer is on the right track. You just need to store the template text in your file. With this in your text file:

Good afternoon {0} your order has shipped.

you can then do something like this:

Dim name = "someone"
Dim template = File.ReadAllText("TextFile1.txt")

RichTextBox1.Text = String.Format(template, name)

The first argument to String.Format is the template, containing the numbered placeholders. The remaining arguments are the values to replace those placeholders. The first of those arguments will replace every instance of "{0}" in the template, the second will replace "{1}" and so on. You need to make sure that your numbered placeholders always match the order of the values you pass to String.Format.

If you don't want the person editing that template to have to remember what each number means, you can write your own replacement code. For instance, you might store this in the file:

Good afternoon {name} your order has shipped.

and then do this:

Private Function FillTemplate(template As String, name As String) As String
    Return template.Replace("{name}", name)
End Function

and this:

Dim name = "someone"
Dim text = FillTemplate(File.ReadAllText("TextFile1.txt"), name)

RichTextBox1.Text = text

You need to add a parameter and a Replace call to FillTemplate for each value you want to insert, e.g.

Private Function FillTemplate(template As String,
                              name As String,
                              address As String) As String
    Return template.Replace("{name}", name).
                    Replace("{address}", address)
End Function
  • Related