How to return a string array from an enum in C#?

So I have a enum and I want to pass it to a ComboBox, so I need it to be an array of strings.

Well, this was much more simple than I thought:

public static string[] EnumToStringArray(Type inType)
{
	return Enum.GetNames(typeof(inType));
}

I found a few sites that were taking some much more complex routes, maybe they didn’t know about this feature.

Working with DateTime and Unix Time Stamps or Universal time (UTC) in C#

Here is the code I used. You should be able to learn everything you need to know by evaluating it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UTC
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dt = DateTime.Now;

            Console.WriteLine("Outputting the type of DateTime object used:");

            Console.WriteLine(dt.Kind);

            Console.WriteLine("\nOutputting the current time as is:");

            Console.WriteLine(dt);

            Console.WriteLine("\nOutputting the current time using the ToUniversalTime() function:");

            Console.WriteLine(dt.ToUniversalTime());

            Console.WriteLine("\nOutputting the current time using the ToFileTime() function:");

            Console.WriteLine(dt.ToFileTime());

            Console.WriteLine("\nOutputting the current time using the ToFileTimeUtc() function:");

            Console.WriteLine(dt.ToFileTimeUtc());

            Console.WriteLine("\nOutputting the current time using the Ticks property:");

            Console.WriteLine(dt.ToFileTimeUtc());

            Console.WriteLine("\nCreating a DateTime and setting it as follows:\nDateTime udt1 = DateTime.Parse(\"1/1/1970\");");

            DateTime udt1 = DateTime.Parse("1/1/1970");

            Console.WriteLine(udt1);

            Console.WriteLine("\nCreating a DateTime and setting it as follows:\nnew DateTime(1970, 1, 1, 0, 0, 0, 0);");

            DateTime udt2 = new DateTime(1970, 1, 1, 0, 0, 0, 0);

            Console.WriteLine(udt1);

            Console.WriteLine("\nOutputting the time stamp of this Unix Time Stamp value: 1254322574 (seconds)\nTo do this i use these lines:\n DateTime udt1 = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n udt.AddSeconds(1254322574448);");

            Console.WriteLine(udt1.AddSeconds(1254322574));

            Console.WriteLine("\nOutputting the time stamp of this Unix Time Stamp value: 1254322574789 (milliseconds)\nTo do this i use these lines:\n DateTime udt1 = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n udt.AddMilliseconds(1254322574448);");

            Console.WriteLine(udt1.AddMilliseconds(1254322574789));

        }
    }
}

Ok, so here is the output:

Outputting the type of DateTime object used:
Local

Outputting the current time as is:
9/30/2009 3:49:18 PM

Outputting the current time using the ToUniversalTime() function:
9/30/2009 9:49:18 PM

Outputting the current time using the ToFileTime() function:
128988209584600486

Outputting the current time using the ToFileTimeUtc() function:
128988209584600486

Outputting the current time using the Ticks property:
128988209584600486

Creating a DateTime and setting it as follows:
DateTime udt1 = DateTime.Parse(“1/1/1970”);
1/1/1970 12:00:00 AM

Creating a DateTime and setting it as follows:
new DateTime(1970, 1, 1, 0, 0, 0, 0);
1/1/1970 12:00:00 AM

Outputting the time stamp of this Unix Time Stamp value: 1254322574 (seconds)
To do this i use these lines:
DateTime udt1 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
udt.AddSeconds(1254322574448);
9/30/2009 2:56:14 PM

Outputting the time stamp of this Unix Time Stamp value: 1254322574789 (milliseconds)
To do this i use these lines:
DateTime udt1 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
udt.AddMilliseconds(1254322574448);
9/30/2009 2:56:14 PM
Press any key to continue . . .

How to check if a SQL Table exists in C#?

Simple question, simple answer

SQL Query to return the data

SELECT TABLE_NAME FROM DBName.INFORMATION_SCHEMA.Tables WHERE TABLE_NAME='Article'

How do I check this in C#?

As for how you check that in C#? You just make sure the Row count returned from the query is 1. See this article I have already posted.

How do I get the number of rows returned from a Microsoft SQL Query in C#?

How to pause a Console application in C# or the equivelent to the C++ system("pause") statement?

How to pause a Console application in C# or the equivelent to the C++ system(“pause”) statement?
I actually had to spend way more time to figure this out. I assumed that there was a simple pause function, but there is not. C# has left out that function. So if you are looking for a way to do this with a single statement, you are not going to find it. I searched, and searched, and searched.

I just wanted to pause, something that is common in C++. In C++ people always do the following:

system("pause");

Note: This is not actually an efficient method to do this in C++. It is loading a cmd.exe process and running the pause command inside it. So should you really be loading a separate external process and all its resources every time you want to pause? Well, it isn’t really that many resources so who really cares, right? You could do the same thing in C# by launching a cmd.exe process but it is probably not what you really want to do.

The best solutions I found are documented, one uses a function, one uses a Pause class.

How to pause a Console application in C#?

Step 1 – Create a function in your Program.cs class called pause as shown here:

public static void Pause()
{
	Console.Write("Press any key to continue . . . ");
	Console.ReadKey(true);
}

Step 2 – Call this function in your code. The following is a complete example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pause
{
    class Program
    {
        static void Main(string[] args)
        {
            Pause();
        }

        public static void Pause()
        {
            Console.Write("Press any key to continue . . .");
            Console.ReadKey(true);
        }
    }
}

How to do this as a Pause class?

Step 1 – Create the following class

Pause.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pause
{
    class Pause
    {
        public Pause()
        {
            Console.Write("Press any key to continue . . .");
            Console.ReadKey(true);
        }
    }
}

Step 2 – Add this to your project and then call new Pause(); and you did it. As

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pause
{
    class Program
    {
        static void Main(string[] args)
        {
            new Pause();
        }
    }
}

How to insert a row into a Microsoft SQL database using C#?

The following example accomplishes this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace InsertToDatabase
{
	public class InsertToDatabase
	{
		string connectionString = @"Data Source = ServerName; user id=UserName; password=P@sswd!; Initial Catalog = DatabaseName;";
		string query = "INSERT INTO Users (Firstname, Lastname, Email) VALUES ('Jared','Barneck','Jared.Barneck@somedomain.tld')";
		SqlConnection connection = new SqlConnection(connectionString);
		SqlCommand command = new SqlCommand(query, connection);
		connection.Open();
		command.ExecuteNonQuery();
		connection.Close();
	}
}

What is the difference between a DataSet and a DataTable?

What is the difference between a DataSet and a DataTable?
Here is a link to the MSDN class information for both:
DataSet Class
DataTable Class

So a DataTable is just a table.

However, a DataSet is a collection of tables that can have their data linked together with a DataRelation Class.

So when accessing a database, which should you use?
Well, if you only need a single table, then just use a DataTable.
However, if you need multiple tables and those tables may have some type of relationship, use a DataSet.

How do I access a MySQL database with C#?

This was a little bit easier for me because I had just figured all this out on Microsoft SQL and (lo and behold), MySQL had created the exact same function structure for MySQL.

So I read through this document first:
Beginning MYSQL 5 with Visual Studio.NET 2005.pdf

It was very informative and showed this code to get into a MySQL database:

string connectionString = "server=ServerName; user id=UserName; password=P@sswd!; database=MyDatabase";
string query = "Select * from users";
MySqlConnection connection = new MySqlConnection(connectionString);
try
{
    connection.Open();
    MySqlDataAdapter dataAdapter = new MySqlDataAdapter(query, connection);
    DataSet dataSet = new DataSet();
    dataAdapter.Fill(dataSet, "users");
}

I had been accessing tables in a Microsoft SQL database using a different set of functions, so I tested to see if the method I had been using for Microsoft SQL would work for MySQL, since the object and function names are almost identical.

The following code also accessed the database and I like it better because a DataTable seems more of an obvious choice to return data from table.

string connectionString = "server=ServerName; user id=UserName; password=P@sswd!; database=MyDatabase";
string query = "Select * from users";
MySqlConnection connection = new MySqlConnection(connectionString);
try
{
    connection.Open();
    MySqlCommand command = new MySqlCommand(query, connection);
    MySqlDataReader reader = command.ExecuteReader();;
    DataTable table = new DataTable();
    table.Load(reader);
}

So I left wondering how these two methods are different…I guess I need to answer the following:

  1. Which of the above two SQL database access methods should be considered best practice and why?
  2. Is one more efficient than the other?
  3. What is the difference between a DataSet and a DataTable?
    DataSet Class
    DataTable Class

How do I get the number of rows returned from a Microsoft SQL Query in C#?

How do I get the number of rows returned from a SQL Query in C#?

Having used other languages where this is much simpler, I was surprised at how “not simple” this was in C#. I expected it to be a little more complex than in some scripting language such as PHP, but it was way more complex.

Here is how I do it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace CountRows
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a string to hold the database connection string
            string sdwConnectionString = @"Data Source = ServerName; user id=UserName; password=P@sswd!; Initial Catalog = DatabaseName;";

            // Create a string to hold the database connection string
            string query = "SELECT * FROM MyTable";

            // Pass both strings to a new SqlCommand object.
            SqlCommand queryCommand = new SqlCommand(query, sdwDBConnection);

            // Create a SqlDataReader
            SqlDataReader queryCommandReader = queryCommand.ExecuteReader();

            // Create a DataTable object to hold all the data returned by the query.
            DataTable dataTable = new DataTable();
            dataTable.Load(queryCommandReader);

            // The DataTable object has a nice DataTable.Rows.Count property that returns the row count.
            int rowCount = rowCount = dataTable.Rows.Count;
        }
    }
}

Now doing it this way, you also have the data available in the DataTable dataTable object so you don’t have to go to the database and get it again.

How I get the number of a rows in a Micorosft SQL table using C#?

How I get the number of rows in a table using C#?

Here is a step by step:

Step 1 – Create a new class: (attached click here: SQLTableRowCounter.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace SQLTableRowCounter
{
    class SQLTableRowCounter
    {
        private string mCountQuery;
        private SqlConnection mConnection;
        private int mNumberOfRows;

        public SQLTableRowCounter(String inTableName, SqlConnection inConnection)
        {
            mCountQuery = "SELECT COUNT(*) FROM " + inTableName;
            mConnection = inConnection;
            mConnection.Open();
            SqlCommand mCountQueryCommand = new SqlCommand(mCountQuery, mConnection);
            mNumberOfRows = (int)mCountQueryCommand.ExecuteScalar();
        }

        public int NumberOfRows
        {
            get { return mNumberOfRows; }
            set { mNumberOfRows = value; }
        }
    }
}

Step 2 – Now create the object and get the value:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace SQLTableRowCounter
{
    class Program
    {
        static void Main(string[] args)
        {
             string connectionString = @"Data Source = ServerName; user id=UserName; password=P@sswd!; Initial Catalog = DatabaseName;";
             SqlConnection connection = new SqlConnection(connectionString);
             SQLTableRowCounter qrc = new SQLTableRowCounter("TableName", connection);
             int numRows = qrc.NumberOfRows;
        }
    }
}