Click here to Skip to main content
15,881,559 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:
Console.WriteLine(
"{0} (quantity {1}) was replaced by {2}, (quantity {3}).", 
item.Description, 
item.Quantity, 
replacement.Description, 
replacement.Quantity);
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
Posted

Why?
Replace it with string.Format:
C#
Console.WriteLine(
   "{0} (quantity {1}) was replaced by {2}, (quantity {3}).", 
   item.Description, 
   item.Quantity, 
   replacement.Description, 
   replacement.Quantity);

C#
myTextBox.Text = String.Format(
   "{0} (quantity {1}) was replaced by {2}, (quantity {3}).", 
   item.Description, 
   item.Quantity, 
   replacement.Description, 
   replacement.Quantity);
 
Share this answer
 
Comments
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

C#
StringBuilder str=new StringBuilder();
str.AppendFormat("{0} (quantity {1}) was replaced by {2}, (quantity {3}).",
                  item.Description,
                  item.Quantity,
                  replacement.Description,
                  replacement.Quantity
                 );
textBox1.Text = str.ToString();
 
Share this answer
 
Comments
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:

C#
//[EDIT...]
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.

[EDIT]

For example, you can use it like this:
C#
class SomeUseOfOutput {
 
   internal SomeUseOfOutput(UiConsole console) { this.Console = console; } 
    
   void OutputExample() {
       Console.WriteLine("Starting...");
       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).

[END EDIT]

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.

—SA
 
Share this answer
 
v3
Comments
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.
--SA
Sergey Alexandrovich Kryukov 18-Jan-12 14:52pm    
If so, please see my update, in [EDIT]. The code block above is updated, too.
--SA
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,
--SA

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