Creating and using a Class File in C#

I will show you the steps to create and use a class file in .NET (C#)

Step 1:

Right Click Project >> Select Add New Item >> Class

Step 2:

Create two functions in your class file.

public DataTable ExecuteSlelectQry(string Query)

{

        SqlConnection oSqlCon = new SqlConnection(FunGenerateConnectionString(StrCompanyCOde));

        DataTable oSqldt = new DataTable();

        try

        {

            using (SqlDataAdapter oSqlda = new SqlDataAdapter(Query, oSqlCon))

            {

                if (oSqlCon.State == ConnectionState.Closed)

                {

                    oSqlCon.Open();

                }

                oSqlda.SelectCommand.CommandTimeout = 0;

                oSqlda.Fill(oSqldt);

                oSqlCon.Close();

            }

        }

        catch (Exception ex)

        {

            if (oSqlCon.State == ConnectionState.Open)

            {

                oSqlCon.Close();

            }

        }

        oSqldt.TableName = "RETURN";

        return oSqldt;

    }

    public bool ExecuteNonSelectQry(string Query)

    {

        SqlConnection oSqlCon = new SqlConnection(FunGenerateConnectionString(StrCompanyCOde));

        try

        {

            using (SqlCommand cmd = new SqlCommand(Query, oSqlCon))

            {

                if (oSqlCon.State == ConnectionState.Closed)

                {

                    oSqlCon.Open();

                }

                cmd.CommandTimeout = 0;

                cmd.ExecuteNonQuery();

                oSqlCon.Close();

            }

            return true;

        }

        catch (Exception ex)

        {

            if (oSqlCon.State == ConnectionState.Open)

            {

                oSqlCon.Close();

            }

            return false;

        }

}

Step 3:

Create the object of the class on your code behind page

Class oClsClass = new Class();

Step 4:

Access the class functions 1

Datatable oDT = new datatable
oDT = oClsClass.ExecuteSlelectQry("Select * from Employees")

Access the class functions 2

oClsClass.ExecuteNonSelectQry("Insert into Employees(EmpName) values("Abcd")"

Ebook Download
View all
Learn
View all