Click here to Skip to main content
14,929,877 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Suppose you have some sample code that uses formatted strings written to the Console: like:
"{0} (quantity {1}) was replaced by {2}, (quantity {3}).", 
And, you'd like to quickly convert all instances of this type of usage to write to an on-screen TextBox, essentially replacing all the {#n} placeholders with their arguments followed by .ToString() ... and of course adding the necessary bracketing quotes, and the string concatenation operator "+."

Any ideas for a quick conversion scheme ?

Another way to ask this is: to ask if I can somehow grab, from within a running WinForm program, the text that results from the use of Console.WriteLine, which normally shows up in the Output window in Visual Studio.

thanks, Bill

Replace it with string.Format:
   "{0} (quantity {1}) was replaced by {2}, (quantity {3}).", 

myTextBox.Text = String.Format(
   "{0} (quantity {1}) was replaced by {2}, (quantity {3}).", 
BillWoodruff 17-Jan-12 9:43am
Thanks, OG ! You are a river unto your people :)

I had just replaced the trial version of ReSharper with a trial version of JustCode, and my IntelliSense seems to have gone out to lunch: I could have sworn I tried using String.Format, without success, though !

Some of the problem in converting this execrable sample code (for the generic KeyedCollection class, which I have been studying) from MSDN, was the sample code's absolutely un-necessary use of static methods in which the reference to 'textBox1 was of course unavailable.

best, Bill
I think you are looking for this

StringBuilder str=new StringBuilder();
str.AppendFormat("{0} (quantity {1}) was replaced by {2}, (quantity {3}).",
textBox1.Text = str.ToString();
BillWoodruff 17-Jan-12 9:46am
Thanks, Rahul, +5: that would work also. best, Bill
I think this would be easier:

Define the Console methods you use with exact same name and signatures:

internal class UiConsole {

    internal UiConsole(TextBox sink) { this.Sink = sink; }

    internal string void WriteLine(string value) { /* this is easy */} 

    internal string void WriteLine() { /* this is easy, too, just use Environment.NewLine */}

    internal string void WriteLine(string format, params object[] values) {
        string stringValue = string.Format(format, values);
        //add stringValue where you want it, for example, add to Sink
    } //WriteLine

    TextBox Sink;

//class UiConsole

Replace Console with you new class somehow, the way you would not need to change a single character in the part of code which writes your output. This is easy, too. Next time, spend some time to write output interface and supply, say, console implementation of it. When you need to direct output somewhere else, just change the implementation.


For example, you can use it like this:
class SomeUseOfOutput {
   internal SomeUseOfOutput(UiConsole console) { this.Console = console; } 
   void OutputExample() {
       Console.WriteLine("Iteration #{0}: x={1}, y={2}", count, x, y);
   } //OutputExample

   UiConsole Console; //same name as System.Console, for easy transition

} //SomeUseOfOutput

In this example, the method OutputExample can work outside of this class if you use using System with System.Console; when you put it in the class SomeUseOfOutput, it starts working with its instance of UiConsole Console and write the same thing to your text box. In this way, there is no need to modify the code of OutputExample in any way.

By the way, I usually do exact same thing, but use ListBox, not TextBox. The TextBox does not have append operation, and appending becomes too expensive if you use Text property and the size of the text buffer becomes too long. I demonstrated high-performance append to TextBox<code> in response to one of the questions; it never uses <code>Text, but manipulates selection and text length, the append is done via assigning the text to be appended to SelectedText property. (In fact, I described the pseudo-code.) With ListBox, you only add a line and adjust scrolling (select new line).


By the way, want to ask you just in case: do you know that you can still use console in the WPF or Forms application (or anywhere)?

Just create a windowed application. Then change the application type to "Console Application" in the project properties. I won't disrupt your application, it will only show a console. "Console Application" simply means: "among other thing, show a console". "Window Application" simply means: hide the console. The names of those types and the fact of using combo box is really misleading. Those types are not alternative to each other as one would think.

BillWoodruff 18-Jan-12 6:02am
+5 Thanks, SAK, for your usual, always high-quality, illumination !

Useful code examples, but I think the task of "Replace Console with your new class somehow" might be difficult ?

I've never written a Console application in my life, and plan to never do so until some fat client send$ :)

best, Bill
Sergey Alexandrovich Kryukov 18-Jan-12 13:58pm
Well, you confuse me, especially with the fact you've never written Console application. Not only it's hard to imagine, but why do you ask this question then? Just getting ready for fat $$$? Well, that's wise. :-)

No matter what, what's about "somehow"? Do you want clarification on that, to show it in sample? I can.
Sergey Alexandrovich Kryukov 18-Jan-12 14:52pm
If so, please see my update, in [EDIT]. The code block above is updated, too.
BillWoodruff 18-Jan-12 16:58pm
Hi SAK, I wish I could vote you another #5 for adding these revisions and extensions on this thread. Thanks !

This question came about because of a temporary failure of IntelliSense in VS Studio, and common sense on my part :)

For whatever reason, I did not locate the overload of String.Format that would have easily taken care of this, and the garbage-worthy MSDN code example for the generic KeyedCollection class (the focus of my study in this case) used some methods defined as 'static (with no organic reason for them to be 'static), that introduced a level of weirdness in trying to substitute an instantiated object (a TextBox) as the target for output rather than Console.

The answer I expected to get here was some interesting hack that re-directed the "standard out" that goes to the Console back to some WinForms target.

It is true I have never written a Console application: never had a need to; but, I mentioned that with an intent for that comment to be humorous, light-hearted, not to cloud the issue at hand :)

In any case, thanks again, for your excellent revision. I think what you've posted here deserves being written up as a Tip/Trick, which would give me a chance to vote it up again.

best, Bill
Sergey Alexandrovich Kryukov 18-Jan-12 18:29pm
You are welcome; and thank you for this comment.
At this moment, I don't think this very tip would deserve a separate Tips/Tricks article, as some of the other tips I've given only in answers are more important or deeper, but still not published in a separate article.

I'm curious about the controversies or unclear aspects of System.Collections.ObjectModel.KeyedCollection<TKey, TItem>. I never payed attention for this class before, but it really looks a bit suspicious to me: why a separate base class for a number of purely applied classes instead of using some class from System.Collections.Generic (or adding a proper abstract class, interface or both in this name space)? Perhaps in needs some thinking. At the same time, I failed to find a single public static member in this class. What methods do you mean? Or do you mean a different class?

Anyway, if you see any problems with this class, it would be interesting if you formulate them in detail in a separate post. I would probably be interested to analyze such concerns.

Thank you,
BillWoodruff 18-Jan-12 19:10pm
Indeed, I think it would be well worth a CP editor's time to "distill" from your copious answers, a whole series of tips and tricks !

My exploration of the rather strange "KeyedCollection" generic class (data structure) was motivated by a mention of it on some thread on StackOverFlow, and I found it interesting that its value is "mixed" in with the key, as well as that it is an abstract class by nature, and that it supports indexed look-up, as well as other typical generic type look-ups.

I'm just spelunking in the caverns of KeyedCollection, not sure what value I may, if ever, find in it.

best, Bill

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900