Showing posts with label C#. Show all posts

[C#] UserControl not displayed in toolbox

[ UserControl not show in toolbox ]
When you create a UserControl, you'll usually see it right in the toolbox after Rebuild Project.
But sometimes you will not see your UserControl in the toolbox, to solve it you can do in the following way:

Open Microsoft Visual Studio 2008 and set this option:
Tools > Options > Windows Forms Designer > General : AutoToolboxPopulate

[C#] Write Text File

This function creates a text file when it runs. In the directory where you give in filePath and strContent you want to write. If you view the contents of this file, you'll see the following textual representation of the date and time when the program last ran.

void WriteTextFile(string filePath, string strContent)
{
    StreamWriter sW = new StreamWriter(filePath);
    sW.Write(strContent);           // Not line breaks
    //sW.WriteLine(strContent);     // Write and line breaks
    sW.Write(DateTime.Now);         // Write Date

    // Flush and Close
    sW.Close();
}

[C#] Read Text file Line by Line

Here is the code to read a text file from disk one line at a time into a string.  This code ensures the file exists and properly closes the file if an exception occurs.
Use these namespaces

using System;
using System.IO;

// Use this function

        private void ReadTextFile(string filePath)
        {
            // initialize line to fill content each line
            string line;
            if (File.Exists(filePath))      // Check existence
            {
                StreamReader file = null;   // initialize Reader
                try
                {
                    file = new StreamReader(filePath);
                    // Read line by line, stop if null.
                    while ((line = file.ReadLine()) != null)   
                    {
                        // === Use each line ===
                        Console.WriteLine(line);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                finally
                {
                    if (file != null)
                        file.Close();
                }
            }
        }