27 Mar

C# Stack Example

The stack represents a simple last-in-first-out (LIFO) non-generic collection of objects.

  • To add an element to the stack, the push method is used. The statement’s general syntax is shown below:
stack.Push("Obj");
  • To remove an element from the stack, the pop method is used. The pop operation returns the stack’s top element. The statement’s general syntax is given below:
object popObj = stack.Pop();

Stack Example:

            Stack stack = new Stack();
            stack.Push("Obj1");
            stack.Push("Obj2");
            stack.Push("Obj3");

            Console.WriteLine("Objects");
            Console.WriteLine("-------");
            foreach (Object obj in stack)
            {
                Console.WriteLine(obj);
            }
            object popObj = stack.Pop();
            Console.WriteLine("Last In/First Out(LIFO): " + popObj);

            Console.WriteLine("The number of elements in the stack: " + stack.Count);
            Console.WriteLine("Contains Obj1:  " + stack.Contains("Obj1"));

Program Output:

stack output

27 Mar

C# Queue Example

The Queue is a special collection which represents first-in, first-out concept of objects.

  • An element is added to the queue using the enqueue method. The statement’s general syntax is shown below:
queue.Enqueue("Obj");
  • To remove an element from the queue, the dequeue method is used. The dequeue operat on returns the queue’s last element. The statement’s general syntax is given below:
object obj = queue.Dequeue();

 

Queue Example:

Queue queue = new Queue();
queue.Enqueue("Obj1");
queue.Enqueue("Obj2");
queue.Enqueue("Obj3");

Console.WriteLine("The number of elements in the Queue: " + queue.Count);
Console.WriteLine("All objects");
foreach (Object obj in queue)
{
     Console.WriteLine(obj);
}

object obj1 = queue.Dequeue();
Console.WriteLine("First: " + obj1);

Console.WriteLine("Contains Obj1: " + queue.Contains("Obj1"));
Console.WriteLine("Contains Obj2: " + queue.Contains("Obj2"));

Program Output:
queue output

27 Mar

C# Hashtable Example

A hash table is a collection that is used to store key-value pairs. So the hash table stores 2 values while storing just one value like the stack, array list and queue. These 2 values are an element of the hash table.

  • To add an element to the queue, the Add method is used. The statement’s general syntax is given below.
ht.Add("key", "Value");
  • ContainsKey method is used to determine whether the Hashtable contains a specific key.
  • ContainsValue method is used to determine whether the Hashtable contains a specific value.

When you use foreach to enumerate hash table elements, the elements are retrieved as KeyValuePair objects.

            foreach (DictionaryEntry de in ht)
            {
                Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
            }

Hastable Example:

            
            Hashtable ht = new Hashtable();
            
            // Add key-value pairs
            ht.Add("key1", "Value1");
            ht.Add("key2", "Value2");
            ht.Add("key3", "Value3");

            bool hasKey1 = ht.ContainsKey("key1");
            bool hasValue2 = ht.ContainsValue("Value1");

            // When you use foreach to enumerate hash table elements,
            // the elements are retrieved as KeyValuePair objects.
            foreach (DictionaryEntry de in ht)
            {
                Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
            }

Program Output:
hashtable output

01 Haz

Select,Insert,Update,Delete Data in MySQL using C#

This example shows how to insert ,update, delete and select data in MySQL.
Firstly, you should install MySql Data Connector program.
https://dev.mysql.com/downloads/connector/net/6.9.html
Then, we need to add a reference to the MySyql.Data

  • Go to solution explorer of your project
  • Select add a reference
  • Click on .Net Tab
  • Select MySql.Data

Add Reference

Select Command Example:

            string connectionString = @"server=localhost;userid=user1;password=12345;database=mydb";

            MySqlConnection connection = null;
            MySqlDataReader reader = null;
            try
            {
                connection = new MySqlConnection(connectionString);
                connection.Open();

                string stm = "SELECT * FROM Customers";
                MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
                dataAdapter.SelectCommand = new MySqlCommand(stm, connection);
                DataTable table = new DataTable();
                dataAdapter.Fill(table);
                return table;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                if (connection != null)
                    connection.Close();
            }

Insert Command Example:

            string connectionString = @"server=localhost;userid=user1;password=12345;database=mydb";

            MySqlConnection connection = null;
            try
            {
                connection = new MySqlConnection(connectionString);
                connection.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = connection;
                cmd.CommandText = "INSERT INTO Customers(Name) VALUES(@Name)";
                cmd.Prepare();

                cmd.Parameters.AddWithValue("@Name", "Bill Gates");
                cmd.ExecuteNonQuery();    
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }

Update Command Example:

            string connectionString = @"server=localhost;userid=user1;password=12345;database=mydb";

            MySqlConnection conn = null;
            MySqlTransaction tr = null;

            try
            {
                conn = new MySqlConnection(connectionString);
                conn.Open();
                tr = conn.BeginTransaction();

                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                cmd.Transaction = tr;

                cmd.CommandText = "UPDATE Customers SET Name='Bill Gates' WHERE Id=1";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "UPDATE Books SET Title='New Title' WHERE Id=2";
                cmd.ExecuteNonQuery();

                tr.Commit();

            }
            catch (MySqlException ex)
            {
                tr.Rollback();
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }

Delete Command Example:

            string connectionString = @"server=localhost;userid=user1;password=12345;database=mydb";
            MySqlConnection connection = null;
            try
            {
                connection = new MySqlConnection(connectionString);
                connection.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = connection;
                cmd.CommandText = "delete from Customers where ID='" + "1" + "';";
                cmd.ExecuteNonQuery();
            }
            finally
            {
                if (connection != null)
                    connection.Close();
            }

See Also: Select,Insert,Update,Delete Data in Access File using C#

10 Eki

C# Get Width And Height of a Window Using Windows API

This example shows how to get width and height of a window using Windows API.

Usage :

            RECT rect;
            UserControl uc = new UserControl();
            if (GetWindowRect(new HandleRef(uc, uc.Handle), out rect))
            {                
                //To do anything  
                int width = rect.Right - rect.Left;
                int height = rect.Bottom - rect.Top;
            }
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowRect(HandleRef hWnd, out RECT lpRect);

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;        // x position of upper-left corner
            public int Top;         // y position of upper-left corner
            public int Right;       // x position of lower-right corner
            public int Bottom;      // y position of lower-right corner
        }