Visual Studio String Functions-CSharp


string sHold = “”;
int nIndex = 0;


//Replaces a string with a specified string.
sHold = “String Test”;
sHold = sHold.Replace(“String”, “Replace”);
//Returns “Replace Test”

//Removes a specified number of characters from a string
//The first number is the starting position, and the last
//number is the ending position.
sHold = “String Test”;
sHold = sHold.Remove(0, 3);
//Result = “ing Test”

//Returns the last index of a specified string.
sHold = “String Test”;
nIndex = sHold.LastIndexOf(“s”);
//Result = 10

//Inserts a string in the specified position.
sHold = “String Test”;
sHold = sHold.Insert(sHold.Length, ” IndexOf”);
//Result = “String Test IndexOf”

//Return the index of a specified string.
sHold = “String Test”;
nIndex = sHold.IndexOf(“r”);
//Result = 3

//Convert To Upper Case
sHold = “String Test”;
sHold = sHold.ToUpper();
//Result = “STRING TEST”

//Convert To Lower Case
sHold = “String Test”;
sHold = sHold.ToLower();
//Result = “string test”

//PadLeft adds specified characters to the beginning of the string.
//The number represents the total length of the resulting string
//including the number of padding characters.
sHold = “String Test”;
sHold = sHold.PadLeft(sHold.Length + 5, Convert.ToChar(” “));
//Result = ” String Test”

//PadRight adds specified characters to the end of the string.
//The number represents the total length of the resulting
string
//including the number of padding characters.
sHold = “String Test”;
sHold = sHold.PadLeft(6, Convert.ToChar(” “));
//Result = “String Test”

sHold = “String Test”;
sHold = sHold.PadRight(sHold.Length + 5, Convert.ToChar(” “));
//Result = “String Test ”

sHold = “String Test”;
sHold = sHold.PadRight(6, Convert.ToChar(” “));
//Result = “String Test”

//EndsWith Determines if a string ends with a specified string and returns
//true or false.
bool bTest = false;
sHold = “String Test”;
bTest = sHold.EndsWith(“Test”);
//Result = true

//StartsWith Determines if a string begins with a specified string and returns
//true or false.
bTest = false;
sHold = “String Test”;
bTest = sHold.StartsWith(“String”);
//Result = true

//Substring returns a string based on the starting index and ending index.
//If the starting or ending specified falls outside the length
of the string,
//an error will be generated.
sHold = “String Test”;
sHold = sHold.Substring(2, 4);
//Result = ring

//Contains determines if a string contains the specified string.
sHold = “String Test”;
bTest = sHold.Contains(“ring”);
//Result = true

//Trims all spaces from beginning and end of specified string.
sHold = ” String Test “;
sHold = sHold.Trim();
//Result = “String Test”

Tagged with: , , , , ,
Posted in Visual Studio Code Examples

Search Engine Features, You May Not Know About

Search engines can be used for more than just searching.  There three major search engines, Google, Bing, and Yahoo, and these search engines can also be used to perform calculations, conversions, return instant weather results, define words, get local time around the world, and return instant stock quotes.

Calculations

If you need to solve a math problem quickly, just navigate to one of the search engines, and type in your math problem, and press the enter key.  The search engine will return the answer.

Listed below are some of the equation symbols:

* = multiplication
/ = division
cos = cosine
sin = sine
sqrt = square root
^ = raised to the power of (5^2 = 25)

Instant Weather Results

If you would like to receive instant weather results, just type weather, the name of the city, and press the Enter Key.

 

Conversions

If you need to convert one unit of measure to another, I.E. km to miles, cups to gallons, etc.  Just type in the conversion you need and press the Enter Key.

Define Words

If you need to know the definition of word, you do not have to go to dictionary.com, just type define and the name of the word you would like to have defined.

Get Local Time Around The World

If you would like to know the current local time of any location in the world, just type local time, the name of the location, and press the Enter Key.

Instant Stock Quotes

If you want to get the current value of a stock, just type in the stock symbol and press the Enter Key.  The current value of the stock will be returned along with a graph of activity for the current day.

Tagged with: , , , , ,
Posted in Search Engine Tips

Display A Directory List In A TextBox Control

Display A Directory List In A TextBox Control

First complete the following steps:

Create a new C# Windows Application in Visual Studio.
Add a button control to the form.
Add a TextBox Control to the form.
Change the Multiline Property of the TextBox Control to ‘True’.
Change the ScrollBars Property of the TextBox Control to ‘Vertical’.
Resize the TextBox Control to fit the Form.

Double Click on the Button Control, and add the code below to the Click Event.


private void button1_Click(object sender, EventArgs e)
{
    //Replace the directory below with a directory on your computer.
    string strDirLocal = @"C:\documents\CodeExamples";
    if (System.IO.Directory.Exists(strDirLocal))
    {
        foreach (string sPath in System.IO.Directory.GetFiles(strDirLocal, "*.*"))
        {
            //Add the file to the TextBox, and remove the Path from the sPath string,
            //leaving the file name.
            textBox1.Text = textBox1.Text + sPath.Replace(strDirLocal + @"\","") + "\r\n";
        }
    }
}
Tagged with: , , , , , ,
Posted in Visual Studio Code Examples

Create a HTML File From a DataGridView Control

First complete the following steps:

Create a new C# Windows Application in Visual Studio.
Add two button controls to the form.
Add a DataGridView Control to the form.


Double Click on the Form and add the code below to the Load Event of the Form:



private void frmDataGridExportHTML_Load(object sender, EventArgs e)
{
    //If you manually add rows to a DataGridView, you must disable the
    //AllowUserToAddRows function.  The function can be enabled after
    //you have added the rows.
    dataGridView1.AllowUserToAddRows = false;

    //The code below adds Columns to the DataGridView control

    DataGridViewColumn colHold = new DataGridViewTextBoxColumn();
    colHold.Name = "col1";
    colHold.HeaderText = "FIELD1";
    dataGridView1.Columns.Add(colHold);

    colHold = new DataGridViewTextBoxColumn();

    colHold.Name = "col2";
    colHold.HeaderText = "FIELD2";
    dataGridView1.Columns.Add(colHold);

    colHold = new DataGridViewTextBoxColumn();

    colHold.Name = "col3";
    colHold.HeaderText = "FIELD3";
    dataGridView1.Columns.Add(colHold);

    colHold = new DataGridViewTextBoxColumn();

    colHold.Name = "col4";
    colHold.HeaderText = "FIELD4";
    dataGridView1.Columns.Add(colHold);

    //The code below adds rows and fills cells with values to be exported.

    dataGridView1.Rows.Add();

    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = "1";
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = "2";
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = "3";
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = "4";

    dataGridView1.Rows.Add();

    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = "5";
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = "6";
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = "7";
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = "8";
}

Double Click on the ‘button1’ Control and add the code below to the Click Event of the button.
This code displays the data from the DataGridView Control in a table format.



private void button1_Click(object sender, EventArgs e)
{
    string sLine = "<table border=" + "\"" + "1" + "\"" + ">";            
    //This line of code creates a html file for the data export.
    System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\HTMLFile1.html");
    file.WriteLine(sLine);
    sLine = "";
    try
    {   
        sLine = "<tr>";
        file.WriteLine(sLine);
        //This for loop places the column headers into the first row of the HTML table.
        for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
        {
            sLine = "<td>" + dataGridView1.Columns[c].HeaderText + "</td>";
            file.WriteLine(sLine);
        }
        sLine = "";

        //This for loop loops through each row in the DataGridView.
        for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
        {
            sLine = sLine + "<tr>";
            file.WriteLine(sLine);
            sLine = "";
            //This for loop loops through each column, and the row number
            //is passed from the for loop above.
            for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
            {
                sLine = "<td>" + dataGridView1.Rows[r].Cells[c].Value + "</td>";
                file.WriteLine(sLine);
            }                                        
            //The exported text is written to the html file, one line at a time.
            sLine = "</tr>";

            file.WriteLine(sLine);
            sLine = "";
        }
        sLine = "</table>";

        file.WriteLine(sLine);
        file.Close();
        System.Windows.Forms.MessageBox.Show("Export Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (System.Exception err)
    {
        System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        file.Close();
    }
}

Double Click on the ‘button2’ Control and add the code below to the Click Event of the button.
This code displays the data in the DataGridView Control in a list format.


private void button2_Click(object sender, EventArgs e)
{
    string sLine = "";
    //This line of code creates a html file for the data export.
    System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\HTMLFile2.html");            
    sLine = "";
    try
    {                
        for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
        {                    
            sLine = "";
            for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
            {
                sLine = dataGridView1.Columns[c].HeaderText + "<br>";
                file.WriteLine(sLine);
                sLine = System.Convert.ToString(dataGridView1.Rows[r].Cells[c].Value) + "<br>";
                file.WriteLine(sLine);
            }                                        
            sLine = "<p>";
            file.WriteLine(sLine);
        }                
        file.Close();
        System.Windows.Forms.MessageBox.Show("Export Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (System.Exception err)
    {
        System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        file.Close();
    }
}

Tagged with: , , , , , ,
Posted in Visual Studio Code Examples

Export To A Text File From A DataGridView Control

Save Data From A DataGridView Control To A Text File

Steps:
Create a new C# project.
Add a button control to Form1.
Add a DataGridView Control to Form1.

Double click on the form, and copy and the code below into the load event of the form.
The code below is optional. The purpose is to put data into the DataGridView Control. If you already have
data in the form, you will not need to use the code below.


        private void Form1_Load(object sender, EventArgs e)
        {
            //If you manually add rows to a DataGridView, you must disable the
            //AllowUserToAddRows function.  The function can be enabled after
            //you have added the rows.
            dataGridView1.AllowUserToAddRows = false;

            //The code below adds Columns to the DataGridView control

            DataGridViewColumn colHold = new DataGridViewTextBoxColumn();
            colHold.Name = "col1";
            colHold.HeaderText = "FIELD1";
            dataGridView1.Columns.Add(colHold);

            colHold = new DataGridViewTextBoxColumn();

            colHold.Name = "col2";
            colHold.HeaderText = "FIELD2";
            dataGridView1.Columns.Add(colHold);

            colHold = new DataGridViewTextBoxColumn();

            colHold.Name = "col3";
            colHold.HeaderText = "FIELD3";
            dataGridView1.Columns.Add(colHold);

            colHold = new DataGridViewTextBoxColumn();

            colHold.Name = "col4";
            colHold.HeaderText = "FIELD4";
            dataGridView1.Columns.Add(colHold);

            //The code below adds rows and fills cells with values to be exported.

            dataGridView1.Rows.Add();

            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = "1";
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = "2";
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = "3";
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = "4";

            dataGridView1.Rows.Add();

            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = "5";
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = "6";
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = "7";
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = "8";

        }

 
Double click on button1 on the form and copy and paste the code below into the click event on the form:

        private void button1_Click(object sender, EventArgs e)
        {
            //This line of code creates a text file for the data export.

            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\TextFile.txt");
            try
            {                
                string sLine = "";

                //This for loop loops through each row in the table
                for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
                {
                    //This for loop loops through each column, and the row number
                    //is passed from the for loop above.
                    for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
                    {
                        sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
                        if (c != dataGridView1.Columns.Count - 1)
                        {
                            //A comma is added as a text delimiter in order
                            //to separate each field in the text file.
                            //You can choose another character as a delimiter.
                            sLine = sLine + ",";
                        }
                    }
                    //The exported text is written to the text file, one line at a time.
                    file.WriteLine(sLine);                     
                    sLine = "";
                }

                file.Close();
                System.Windows.Forms.MessageBox.Show("Export Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception err)
            {
                System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                file.Close();
            }
        }





Realated Posts:

Display A Text File In A DataGridView
Write To A Text File
Dynamically Populate A DataGridView

Tagged with: , , , , , ,
Posted in Visual Studio Code Examples

Dynamically Create and Execute a Batch File Using Visual Studio

Create a directory called “c:\bat”.
Create a directory called “c:\zip”.

Copy some .zip files to “c:\zip”

Create a new Visual Studio C# application.
Add a button to Form1.
Double click on button1 and copy and paste the code below into the Click event.

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        //This will create a new .bat file in the bat directory.
        System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\bat\dirlist.bat");
        //The code below will write lines to the .bat file.
        //The dir command is used in a Command to list files in the specified directory.
        //The > command in this case sends the list to a text file.
        file.WriteLine(@"dir C:\Zip\*.zip > C:\bat\dir.txt");
        file.WriteLine("exit");
        file.Close();

        //The System.Dignostics.Process Process Class allows a Visual Studio Program
        //to execute another application
        System.Diagnostics.Process proc = new System.Diagnostics.Process();

        proc = new System.Diagnostics.Process();

        proc.EnableRaisingEvents = false;
        //This line executes the .bat file created above.
        proc.StartInfo.FileName = @"C:\bat\dirlist.bat";
        proc.Start();
    }
    catch (System.Exception err)
    {
        System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
Tagged with: , , , , ,
Posted in Visual Studio Code Examples

Display A Text File In A DataGridView

Create a text file on your hard drive, copy and paste this code into the text file, and save your changes.

FIELD1;FIELD2;FIELD3;FIELD4
1;2;3;4
5;6;7;8
9;10;11;12
13;14;15;16

Complete the following steps:

Create a new Visual Studio C# Application.

Add a DataGridView Control to Form1.
Add a Button Control to Form1.
Add an OpenFileDialog Control to Form1.



Copy and paste the code below into the click event of the button:

       private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
            {

                String sLine = "";

                try
                {
                    //Pass the file you selected with the OpenFileDialog control to
                    //the StreamReader Constructor.
                    System.IO.StreamReader FileStream = new System.IO.StreamReader(openFileDialog1.FileName);
                    //You must set the value to false when you are programatically adding rows to
                    //a DataGridView.  If you need to allow the user to add rows, you
                    //can set the value back to true after you have populated the DataGridView
                    dataGridView1.AllowUserToAddRows = false;

                    //Read the first line of the text file
                    sLine = FileStream.ReadLine();
                    //The Split Command splits a string into an array, based on the delimiter you pass.
                    //I chose to use a semi-colon for the text delimiter.
                    //Any character can be used as a delimeter in the split command.
                    string[] s = sLine.Split(';');                    

                    //In this example, I placed the field names in the first row.
                    //The for loop below is used to create the columns and use the text values in
                    //the first row for the column headings.
                    for (int i = 0; i <= s.Count() - 1; i++)
                    {
                        DataGridViewColumn colHold = new DataGridViewTextBoxColumn();
                        colHold.Name = "col" + System.Convert.ToString(i);
                        colHold.HeaderText = s[i].ToString();
                        dataGridView1.Columns.Add(colHold);
                    }

                    //Read the next line in the text file in order to pass it to the
                    //while loop below
                    sLine = FileStream.ReadLine();
                    //The while loop reads each line of text.
                    while (sLine != null)
                    {
                        //Adds a new row to the DataGridView for each line of text.
                        dataGridView1.Rows.Add();

                        //This for loop loops through the array in order to retrieve each
                        //line of text.
                        for (int i = 0; i <= s.Count() - 1; i++)
                        {
                            //Splits each line in the text file into a string array
                            s = sLine.Split(';');
                            //Sets the value of the cell to the value of the text retreived from the text file.
                            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[i].Value  = s[i].ToString();
                        }
                        sLine = FileStream.ReadLine();
                    }
                    //Close the selected text file.
                    FileStream.Close();
                }
                catch (Exception err)
                {
                    //Display any errors in a Message Box.
                    System.Windows.Forms.MessageBox.Show("Error:  " + err.Message, "Program Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

After you add the code to the button click event,
start the application, click 'Button1', and select
the text file, you created earlier.
Tagged with: , , , , ,
Posted in Visual Studio Code Examples

Visual Studio Write to a Text File

Visual Studio C# Write to a File:

In order to test this code, do the following:

Create a new Windows Application

Add a New form

Add a textbox to the form; use the default name for the textbox.

Make sure to change the Multiline Property of the textbox to True.

After changing the Multiline Property of the textbox to True, make the textbox larger in order to fill the form, but leave enough room at the top to add a button.

Add a button to the form above the textbox.

Rename the button, ‘pbSave’.

Paste the code below into the Click event of the ‘Save’ button.

Type some text into the text box, and click the ‘Save’ button.

       

 private void pbSave_Click(object sender, EventArgs e)
        {

            try
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Test\TextFile.txt");
                file.WriteLine(textBox1.Text);
                file.Close();
            }
            catch (System.Exception err)
            {
                System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


Related post:
Visual Studio-Reading From A Text File 
Tagged with: , , , , ,
Posted in Visual Studio Code Examples

Facebook Tip – Find Out What Other Facebook Users Are Posting

If you happen to be a University of Alabama fan, and a Facebook user, and you would like to know who is currently posting about your favorite team.

Do the following:

In the ‘Search’ box in the top center of the Facebook page, type ‘Roll Tide’, and click the magnifying glass.
Click ‘Posts By Everyone’, and you will see everyone who has recently posted ‘Roll Tide’ in their status.

If you are a Facebook User, and are currently logged in, you can see the results by clicking on the link below:

http://www.facebook.com/search.php?q=roll%20tide&init=quick&tas=0.4991310271434486&type=eposts

This works with any phrase, like ‘Cheese Head’:

http://www.facebook.com/search.php?q=%22Cheese%20Head%22&init=quick&tas=0.8197562310378999&type=eposts

Or ‘Terrible Towel’:

http://www.facebook.com/search.php?q=%22Terrible%20Towel%22&init=quick&tas=0.996547520859167&type=eposts

Or ‘obamacare’:

http://www.facebook.com/search.php?q=obamacare&init=quick&tas=0.08406723220832646&type=eposts

Or ‘Conservative’:

http://www.facebook.com/search.php?q=Conservative&init=quick&tas=0.702930340077728&type=eposts

Or ‘Christian’:

http://www.facebook.com/search.php?q=Christian&init=quick&tas=0.6937496631871909&type=eposts

Tagged with: ,
Posted in Facebook Tips

Oracle-Use ROWNUM To Return Row Count

Oracle ROWNUM Reserved Field

Use reserved field, ROWNUM in SELECT Statement to return record number in the data output:

SELECT ROWNUM, FIELD1, FIELD2, FIELD3 FROM YOUR_TABLE

Returns:

ROWNUM	        FIELD1		FIELD2		FIELD3
1		F1VAL1		F2VAL1		F3VAL1
2		F1VAL2		F2VAL2		F3VAL2
3		F1VAL3		F2VAL3		F3VAL3
4		F1VAL4		F2VAL4		F3VAL4
5		F1VAL5		F2VAL5		F3VAL4
Tagged with: , ,
Posted in Oracle
%d bloggers like this: