I am very new c# , the code i wrote constantly sends the data to console i.e console.writeline. the class is called generate_data

i created another GUI class that contains a textbox.

i want to redirect all the output of generate_data to the textbox.
everytime generate_data class produces output it should be send to the textbox.

Recommended Answers

All 12 Replies

In your Generate_data constructor set your GUI class as a parameter, and in your GUI class write a property to access your TextBox.

class Generate_data
    {
        public Generate_data(GUI parent)
        {
            this.parent = parent;
        }

        public void Method()
        {
            //Console.WriteLine("some text");
            parent.TextBoxWrite = "some text";
        }

        GUI parent;
    }
    class GUI : Form
    {
        public GUI()
        {
            Generate_data data = new Generate_data(this);
        }
        public string TextBoxWrite
        {
            set
            {
                textBox1.Text = value;
            }
        }
    }

hi volgent
thank you and much appreciate your quick reply, i learn something new from you.
there is one problem with this code. it overrides the previous values in textbox generated by generate_data class. i want textbox to show all the values i.e. as the values are generated by generate_data class, the values should be passed to textbox in new line instead of overriding.

Then, I think, you need some kind of such function, instead of TextBoxWrite property:

public void AppendText(string new_str)
        {
            StringBuilder data = new StringBuilder();
            data.Append(textBox1.Text);
            data.AppendLine(new_str);
            textBox1.Text = data.ToString();
        }

I used StringBuilder instead String type only because I prefer it. =)

i want textbox to show all the values i.e. as the values are generated by generate_data class, the values should be passed to textbox in new line instead of overriding.

Or change line 26 to textBox1.Text +=value;

thanks guys, both ideas work. but its not suitable the generate_data class constanlty produces data for infinite time. please see the code below. its not suitable because the form class waits until generate_data class finish its task.
My aim is that whenever generate_data produces value(s), the textbox in form should immediately show the values.Hope iam able to explain what iam trying to achieve. please assist me. the code perfectly works fine and you see the the issues with this procedure

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Text; 
using System.Threading;


	public class MainForm : Form
	{
	TextBox textBox1;
	
	Button buttonStart  = new Button();
    Button buttonExit=new Button();

  
		public MainForm()
		{

			 InitializeComponent();

		}
		public void InitializeComponent()
{
 
  
  Panel panel2 = new Panel(); //panel 2 contains the textbox to input values to watcher program
  panel2.Location=new Point(50,32);
  panel2.Size=new Size(200,200);
  panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
  
  
  buttonStart.Location = new Point(10, 100);
  buttonStart.Text = "Start";
  buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
    //program exit button
  buttonExit.Location=new Point(80,100);
  buttonExit.Text="exit";
  buttonExit.Click += new System.EventHandler(this.buttonExit_Click);

  
  this.Controls.Add(panel2);
  
  panel2.Controls.Add(buttonStart);
  panel2.Controls.Add(buttonExit);

  Panel panel1 = new Panel(); 
  textBox1 = new TextBox();
  Label label1 = new Label();
  
  // Initialize the Panel control.
  panel1.Location = new Point(300,32);
  panel1.Size = new Size(200, 300);
 
  // Set the Borderstyle for the Panel to three-dimensional.
  panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
 
  // Initialize the Label .
  label1.Location = new Point(10,10);
  label1.Text = "Logs";
  label1.Size = new Size(104, 30);
  
  //log textbox
  textBox1.Location = new Point(30,40);
  textBox1.Multiline=true;
  textBox1.Size = new System.Drawing.Size(150,250);
  textBox1.ScrollBars=ScrollBars.Both;
  //textBox1.Text=info;
 
  // Add the Panel control to the form.
  this.Controls.Add(panel1);
 
  // Add the Label and TextBox controls to the Panel.
  panel1.Controls.Add(label1);
  panel1.Controls.Add(textBox1);
  
}
		public void buttonStart_Click(object sender, System.EventArgs e)
		{
			Generate_data generate_data = new Generate_data(this);
			generate_data.calc(2,3);
		}
		
		public void buttonExit_Click(object sender, System.EventArgs e)
		{
			Application.Exit();
		}
		/*
		public string textbox
		{
			set
			{
				textBox1.Text+=value +"\r\n";
			}
		}
		*/
		public void appendtext(string str)
		{
			StringBuilder stringbuilder= new StringBuilder();
			stringbuilder.Append(textBox1.Text);
			stringbuilder.Append(str +"\r\n");
			textBox1.Text=stringbuilder.ToString();
		}
		
		
	}
	

public class Generate_data
{
	double b=0;
	double h=0;
	//int i=0;
	int rate=2;
	public Generate_data (MainForm parent)
	{
		this.parent=parent;
	}
	MainForm parent;
	public void calc(double b, double h)
	{ for (int loop=0;loop * rate<36;loop++)
	  
		{
			for (int i=0;i<10;i++)
		
			{
		
		this.b=b;
		this.h=h;
		
		
		double res=i* b*h;
		string result=Convert.ToString(res);
		//parent.textbox=result;
		//System.Threading.Thread.Sleep(1000);
		parent.appendtext(result);
		
		}
			System.Threading.Thread.Sleep(rate*1000);
		}
		
	}
}
	



public class maincl
{
	public static void Main(string[] args) 
	{
		MainForm mainform=new MainForm();
		mainform.Size=new Size(600,400);
		mainform.ShowDialog();
		
	}
}

Thread will improve the performance of your app.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

public class MainForm : Form
{
    TextBox textBox1;

    Button buttonStart = new Button();
    Button buttonExit = new Button();
    StringBuilder stringbuilder;

    public MainForm()
    {
        InitializeComponent();
    }
    public void InitializeComponent()
    {

        Panel panel2 = new Panel(); //panel 2 contains the textbox to input values to watcher program
        panel2.Location = new Point(50, 32);
        panel2.Size = new Size(200, 200);
        panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;


        buttonStart.Location = new Point(10, 100);
        buttonStart.Text = "Start";
        buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
        //program exit button
        buttonExit.Location = new Point(80, 100);
        buttonExit.Text = "exit";
        buttonExit.Click += new System.EventHandler(this.buttonExit_Click);


        this.Controls.Add(panel2);

        panel2.Controls.Add(buttonStart);
        panel2.Controls.Add(buttonExit);

        Panel panel1 = new Panel();
        textBox1 = new TextBox();
        Label label1 = new Label();

        // Initialize the Panel control.
        panel1.Location = new Point(300, 32);
        panel1.Size = new Size(200, 300);

        // Set the Borderstyle for the Panel to three-dimensional.
        panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;

        // Initialize the Label .
        label1.Location = new Point(10, 10);
        label1.Text = "Logs";
        label1.Size = new Size(104, 30);

        //log textbox
        textBox1.Location = new Point(30, 40);
        textBox1.Multiline = true;
        textBox1.Size = new System.Drawing.Size(150, 250);
        textBox1.ScrollBars = ScrollBars.Both;
        //textBox1.Text=info;

        // Add the Panel control to the form.
        this.Controls.Add(panel1);

        // Add the Label and TextBox controls to the Panel.
        panel1.Controls.Add(label1);
        panel1.Controls.Add(textBox1);

    }
    public void buttonStart_Click(object sender, System.EventArgs e)
    {
        stringbuilder = new StringBuilder();
        Generate_data generate_data = new Generate_data(this);
        System.Threading.ParameterizedThreadStart ps = new System.Threading.ParameterizedThreadStart(generate_data.calc);
        System.Threading.Thread thread = new System.Threading.Thread(ps);
        ps.Invoke(new double[] { 2, 3 });

    }

    public void buttonExit_Click(object sender, System.EventArgs e)
    {
        Application.Exit();
    }

    
    public void appendtext(string str)
    {
        stringbuilder.Append(str + "\r\n");
        textBox1.Text = stringbuilder.ToString();
        textBox1.Update();
    }
}


public class Generate_data
{
    double b = 0;
    double h = 0;
    //int i=0;
    int rate = 2;
    public Generate_data(MainForm parent)
    {
        this.parent = parent;
    }
    MainForm parent;

    public void calc(object obj)
    {
        double b, h;
        double[] ar = (double[])obj;
        b = ar[0];
        h = ar[1];
        for (int loop = 0; loop * rate < 36; loop++)
        {
            for (int i = 0; i < 10; i++)
            {

                this.b = b;
                this.h = h;


                double res = i * b * h;
                string result = Convert.ToString(res);
                parent.appendtext(result);
            }
        }

    }
}

Thread will improve the performance of your app.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

public class MainForm : Form
{
    TextBox textBox1;

    Button buttonStart = new Button();
    Button buttonExit = new Button();
    StringBuilder stringbuilder;

    public MainForm()
    {
        InitializeComponent();
    }
    public void InitializeComponent()
    {

        Panel panel2 = new Panel(); //panel 2 contains the textbox to input values to watcher program
        panel2.Location = new Point(50, 32);
        panel2.Size = new Size(200, 200);
        panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;


        buttonStart.Location = new Point(10, 100);
        buttonStart.Text = "Start";
        buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
        //program exit button
        buttonExit.Location = new Point(80, 100);
        buttonExit.Text = "exit";
        buttonExit.Click += new System.EventHandler(this.buttonExit_Click);


        this.Controls.Add(panel2);

        panel2.Controls.Add(buttonStart);
        panel2.Controls.Add(buttonExit);

        Panel panel1 = new Panel();
        textBox1 = new TextBox();
        Label label1 = new Label();

        // Initialize the Panel control.
        panel1.Location = new Point(300, 32);
        panel1.Size = new Size(200, 300);

        // Set the Borderstyle for the Panel to three-dimensional.
        panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;

        // Initialize the Label .
        label1.Location = new Point(10, 10);
        label1.Text = "Logs";
        label1.Size = new Size(104, 30);

        //log textbox
        textBox1.Location = new Point(30, 40);
        textBox1.Multiline = true;
        textBox1.Size = new System.Drawing.Size(150, 250);
        textBox1.ScrollBars = ScrollBars.Both;
        //textBox1.Text=info;

        // Add the Panel control to the form.
        this.Controls.Add(panel1);

        // Add the Label and TextBox controls to the Panel.
        panel1.Controls.Add(label1);
        panel1.Controls.Add(textBox1);

    }
    public void buttonStart_Click(object sender, System.EventArgs e)
    {
        stringbuilder = new StringBuilder();
        Generate_data generate_data = new Generate_data(this);
        System.Threading.ParameterizedThreadStart ps = new System.Threading.ParameterizedThreadStart(generate_data.calc);
        System.Threading.Thread thread = new System.Threading.Thread(ps);
        ps.Invoke(new double[] { 2, 3 });

    }

    public void buttonExit_Click(object sender, System.EventArgs e)
    {
        Application.Exit();
    }

    
    public void appendtext(string str)
    {
        stringbuilder.Append(str + "\r\n");
        textBox1.Text = stringbuilder.ToString();
        textBox1.Update();
    }
}


public class Generate_data
{
    double b = 0;
    double h = 0;
    //int i=0;
    int rate = 2;
    public Generate_data(MainForm parent)
    {
        this.parent = parent;
    }
    MainForm parent;

    public void calc(object obj)
    {
        double b, h;
        double[] ar = (double[])obj;
        b = ar[0];
        h = ar[1];
        for (int loop = 0; loop * rate < 36; loop++)
        {
            for (int i = 0; i < 10; i++)
            {

                this.b = b;
                this.h = h;


                double res = i * b * h;
                string result = Convert.ToString(res);
                parent.appendtext(result);
            }
        }

    }
}

hi adatapost
thank you for your quick reply but does not improve the performance. My aim is that as soon as generate_data class produces value(s) it should show immedialty in textbox.

>My aim is that as soon as generate_data class produces value(s) it should show immedialty in textbox.

Have you noticed line #96 - textBox1.Update() will update the content periodically.

If you want to redirect your Console.Writeline messages to a textbox then you should create a class inheriting Sytem.IO.TextWriter just like:

public class ConsoleStreamHandler : TextWriter
    {
        private TextBox output = null;

        public ConsoleStreamHandler(ref TextBox output)
        {
            this.output = output;
        }

        public override void Write(char value)
        {
            base.Write(value);

            MethodInvoker action = delegate
            {
                this.output.AppendText(value.ToString());
            };

            if (output.InvokeRequired)
                output.BeginInvoke(action);
            else
                action.Invoke();
        }

        public override Encoding Encoding
        {
            get { return System.Text.Encoding.ASCII; }
        }
    }

Then on your form you just need to create the instance of this object and pass the reference of your textbox on it. Then do somewhere on your code preferably after the handle is created or on load of your form.

ConsoleStreamHandler windowOutput = new ConsoleStreamHandler( ref textbox );
 Console.SetOut( windowOutput );

Whenever you call Console.Writeline("some text") this will be redirected to you textbox.

By the way if you're doing some windows form programming you should be aware of cross-thread scenario. This kind of error occurs whenever another thread is trying to update your windows component independently. If you'll look on my code I provided a delegate and use BeginInvoke to ensure that we don't encounter cross-thread errors. Please search on delegates and cross-thread discussions to help you even further on your development.

Thread do help us processe faster and parallel with other transactions but it does not always equate to that benefits alone. If you don't know what you're doing around threads then you'll just make your application go 100% and other synchronization errors. .Net framework provides us with classes for thread polling and asynchronous processing. Better research on it specially background worker class since you're on gui programming.

thanks mate, i agree it updates periodically, but the prgram is smooth. e.g. when generate_data class is producing values user cannot move the scrollbar and also if the user want to exit the programe. user don't have any control over the form when generate_data class is producing values.

thanks for ur assistance, i do understand what u r trying to say, but can u please guide me.. what this class ConsoleStreamHandle task.

If you want to redirect your Console.Writeline messages to a textbox then you should create a class inheriting Sytem.IO.TextWriter just like:

public class ConsoleStreamHandler : TextWriter
    {
        private TextBox output = null;

        public ConsoleStreamHandler(ref TextBox output)
        {
            this.output = output;
        }

        public override void Write(char value)
        {
            base.Write(value);

            MethodInvoker action = delegate
            {
                this.output.AppendText(value.ToString());
            };

            if (output.InvokeRequired)
                output.BeginInvoke(action);
            else
                action.Invoke();
        }

        public override Encoding Encoding
        {
            get { return System.Text.Encoding.ASCII; }
        }
    }

Then on your form you just need to create the instance of this object and pass the reference of your textbox on it. Then do somewhere on your code preferably after the handle is created or on load of your form.

ConsoleStreamHandler windowOutput = new ConsoleStreamHandler( ref textbox );
 Console.SetOut( windowOutput );

Whenever you call Console.Writeline("some text") this will be redirected to you textbox.

By the way if you're doing some windows form programming you should be aware of cross-thread scenario. This kind of error occurs whenever another thread is trying to update your windows component independently. If you'll look on my code I provided a delegate and use BeginInvoke to ensure that we don't encounter cross-thread errors. Please search on delegates and cross-thread discussions to help you even further on your development.

Thread do help us processe faster and parallel with other transactions but it does not always equate to that benefits alone. If you don't know what you're doing around threads then you'll just make your application go 100% and other synchronization errors. .Net framework provides us with classes for thread polling and asynchronous processing. Better research on it specially background worker class since you're on gui programming.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.