Variable Declaration and Initialization in C#

Let’s see how to declare and initialize variables in C#.

A variable is a name given to a memory location where the value is stored. These variables have a data type based on the value stored in them.

Syntax for variable declaration: data_type variable_name;
Example for variable declaration: int age;
NOTE: You will get compilation error if you use a variable before assigning an initial value.

To avoid this compilation error, you can assign a default value to the variable at the time of declaration. You can combine variable declaration and initialization in the same line. You assign a value to a variable using = sign.
For example: int age = 20;

Below is sample code:

 

Sample Console Aplication

C# programs can be created in many ways like Windows Forms Application, Console Application etc. Let’s create a sample console application “Hello World”. I am using Microsoft Visual Studio Ultimate 2013.

    • Open Visual Studio –> Click on New Project.
    • Select Console Application from the given templates. Give your project a friendly name, without any spaces. Click OK. This will create a new project.

      • When the project is created, you will see the below screen. The default class is Program and default function is Main() which defines the entry point of the application.

    • Copy the below code in your Main() function.
      Console.WriteLine("Hellow World!");
      Console.ReadLine();
      Your program will look like:


Console.Write() writes the text representation of the specified value or values to the standard output stream.
Console.WriteLine() writes the text representation of the specified object, followed by the current line terminator, to the standard output stream.
Console.Readline() reads the next line of characters from the standard input stream.

    • Press F5 to run the program. You will see below output on Command Prompt.

Miscellaneous Points – DotNet

  • In C#, it is not possible to create global functions or global points of data. Rather all data members and all methods must be contained within a type definition like within a class.
  • C# is a case-sensitive language.
  • All C# keywords are lowercase like public, static, class etc., while namespace, types and member name uses CAML-casing like Console, WriteLine, MessageBox etc.
  • Whenever you receive a compiler error regarding “undefined symbols”, be sure to check the spellings and casing first.
  • There can be more than one Main() method in the program, but you must inform the compiler which Main() method should be used as the entry point either via /main option of the command-line compiler or via the Startup Object drop down list box, located under Application tab of Visual Studio project properties editor.
  • Main() method has a single parameter, args[], which is an array of string. This parameter may contain any number of incoming command-line arguments. Main() method is uses static and void keywords. static members are scoped to class level rather than object level, thus can be invoked without the need to first create a new class instance. void return value means we do not explicitly define a return value using the return keyword before exiting the method scope.
  • // is used to make single line comments. /*    */ is used to make multiple line comments.
  • Statements in C# language are terminated by semicolon (;).
  • We cannot define overloaded method if it differs from another method only on out and ref.

Check if value exist in database using C#

Sometimes we need to check whether a value exists in a particular column of database table or not. Below is the C# code for the same:

public static int checkExistingCustomerName(string custName)
{
     string strCmd = "SELECT COUNT(CustomerName) FROM CustomerDetails WHERE CustomerName='" + custName + "'";
     string custID;
     using (OleDbConnection conn = new OleDbConnection(Constants.connectionString))
     {
          try
          {
               OleDbCommand cmd = new OleDbCommand(strCmd, conn);
               conn.Open();
               object obj = cmd.ExecuteScalar();
               if (obj == DBNull.Value || Convert.ToInt32(obj)==0)
                    return 0;
               else
                    return 1;
           }
           catch (Exception ex)
           {
               return 1000;
           }
      }
}

AutoFill the data from a particular column from DataBase into a ComboBox

In this article, we will autofill the CustomerNames from CustomerDetails table in a ComboBox on FormLoad event.
Create a CobmoBox say cmbCustomerName on your form.

Write the following code in the FormLoad event of your code.
Use the code for getCustomerDetails() function from https://tutorials4sharepoint.wordpress.com/2017/11/08/get-all-the-data-from-a-table-in-ms-access-database-using-c-ado-net/ post.

DataTable custDt = new DataTable();
custDt = getCustomerDetails();
cmbCustomerName.DataSource = custDt;
if(custDt!=null)
{
     cmbCustomerName.BindingContext = this.BindingContext;
     cmbCustomerName.DisplayMember = "CustomerName";
     cmbCustomerName.ValueMember = "CustomerID";
     cmbCustomerName.Text = "-Select Option-";
}
else
     cmbCustomerName.Text = "No Customer Data Available!";

Create the AutoGenerated Sequential ID in C#

In this article, we will fetch the last entered ID say CustomerID from the CustomerDetails table of the MS Access Database and increment it by 1. We can use this ID anywhere in our application say to use it in the new record etc.

NOTE: If you are using SQL Database, you can replace OleDbConnection and OleDbCommand with SQLConnection and SQLCommand respectively.

If there is no record in the table, this code also checks for that null condition and start the ID from a particular value say 100. We are returning the ID for it to be used at other places in our application.

public static string getCutomerID()
{
     string strCmd = "SELECT MAX(CustomerID) FROM CustomerDetails";
     string custID;
     using(OleDbConnection conn=new OleDbConnection(connectionString))
     {
            try
            {
                OleDbCommand cmd = new OleDbCommand(strCmd, conn);
                conn.Open();
                object obj = cmd.ExecuteScalar();
                if (obj == DBNull.Value)
                    custID = "100";
                else
                    custID = (Convert.ToInt32(obj) + 1).ToString();
                 return custID;
           }
           catch (Exception ex)
           {
                return null;
           }
      }
}

You can use this function to display CustomerID in a TextBox, txtCustomerID:

txtCustomerID.Text= getCutomerID();

Miscellaneous Code – DotNet

Add Values in ComboBox in C#:

cmbCustomerName.Items.Add("Akanksha");

Get the selected item value from combo Box:

string customerName = cmbCustomerName.GetItemText(cmbCustomerName.SelectedItem);

Show current Date and Time:

lbldate.Text=DateTime.Now.ToString();

Connection String to connect Visual Studio C# Windows Form Application to MS Access .accdb Database:

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\DailyExpenses.accdb";

Check for zero rows in a DataTable:

if(dataTable==null){......}

Fetch DataTable CellValue into a variable:

txtCustomerID.Text = custDt.Rows[0]["CustomerID"].ToString();

Enter only numbers and Backspace in TextBox:

private void txtCustomerPhone_KeyPress(object sender, KeyPressEventArgs e)
{
     e.Handled = !(char.IsDigit(e.KeyChar) || e.KeyChar == 8);
}

Add values from one ListBox to Another ListBox. Remove values from a ListBox.

We will demonstrate how to copy value from one ListBox to another ListBox without deleting the values from the list box. Lets create two listboxes: lstAvailableItems and lstSelectedItems AND two buttons: btnAdd and btnRemove.

Below is the code to add items from lstAvailableItems to lstSelectedItems after clicking the Add button. We can remove the items from lstSelectedItems by clicking Remove button.

Below is the design of the form used for this example.

private void btnAdd_Click(object sender, EventArgs e)
{
     string lstboxItem = lstAvailableItems.GetItemText(lstAvailableItems.SelectedItem);
     lstSelectedItems.Items.Add(lstboxItem);
     lstAvailableItems.GetItemText(lstAvailableItems.SelectedItem);
}

private void btnRemove_Click(object sender, EventArgs e)
{
     lstSelectedItems.Items.Remove(lstSelectedItems.GetItemText(lstSelectedItems.SelectedItem));
}

Connect to .accdb instead of .mdb Access database

We sometimes face issues while connecting to .accdb Access Database instead of .mdb Access Database.

For this, we use different Provider while declaring our Connection String.

string connectionString = @”Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\DailyExpenses.mdb“;

For .mdb, we use Microsoft.Jet.OLEDB.4.0 Provider.

For .accdb, we use Microsoft.ACE.OLEDB.12.0 Provider.

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started