Friday, July 3, 2015

How do i bind aspxgridview to object data source?

ASPxGridView OnDataBinding

If you are a beginner in DevExpress and you need to utilize the data grid function of devexpress; the aspxgridview, to display data and later perform CRUD functions on aspxgridview, this might give you a headstart. As you read on the examples on the hows on aspxgridview provided by the DevExpress team, you will notice that they provide only a simple direct binding which is via datasource properties from the aspxgridview to SQLdata source. There is of course, an example on how to bind aspxgridview with data objects, however,i still wish that my approach will help the beginners in aspxgridview, especially asp.net newcomers or students to be able to start exploring the beauty of devExpress!

Now to the code!

Suppose you are to display data from a specific table in database to an aspxgridview data grid. In this example, i will be using the sys_user table from my database which stores the user's data. Below is the structure of the sys_user table.

Figure 1 : sys_user table structure
The newly created aspgridview will display the Username,Fullname, stored inside the sys_user table, and the Status which will be set based on the IsActive column. If IsActive is 0, the Status will be 'Not Active' and vice versa.

Another important thing to be mentioned before we proceed to aspxgridview databinding, is the architecture of the code to be implemented. For this tutorial,i will implement the tri-layer architecture of asp.net which includes separation of interface,business layer and data access layer. Read here to find out more about asp.net three-layer architecture.

Step 1
Create a new devExpress asp.net project from your VS. In your aspx page, drag and drop, or add the aspxgridview controls to your aspx page.

Step 2
Add the KeyFieldName, AutoGenerateColumns properties and OnDataBinding, and OnInit events to the aspxgridview :

Figure 2 : Adding Grid

i. KeyFieldname
-This will be the unique id from your table or the Primary key that wont be repeated anywhere else in the table. In this tutorial it will be the UserID .
ii. AutoGenerateColumns
-Set this property to false to disable auto columns generation in aspxgridview. In this tutorial, i will only be using UserId,Fullname,Username and IsActive from the table. I do not want the aspxgridview to be populated with all the columns from the table.
iii.OnInit(Event)
-It is a good approach to start data binding in the OnInit event rather than the page_load or the grid OnLoad. The OnInit event is the first event that occurs in the aspxgridview page life cycle.
iv. OnDataBinding (Event)
- The OnDataBinding event is triggered when the .DataBind() method is called. It is a good practice to utilize this event as it will easier to bind and rebind the aspxgridview upon CRUDs.I will explain more on this in future tutorial.



Step 3
Add the Columns properties to choose which data will be displayed from the object class or table. In this tutorial i will be displaying 3 columns in the aspxgridview, Username,Fullname and Status. So,we will add 3 dx:GridViewDataTextColumn into the gridview.

Figure 3: Adding Columns
i. FieldName
- make sure the Fieldname property matches the Object in your object class.

Step 4
Now we move to the code behind and class. Lets create a class that will store the objects. Lets name this class ObjectClass. This class will serve as the business logic layer.

ObjectClass.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//add
using System.Data;

namespace aspxgridviewBlogDataBinding
{
    public class ObjectClass
    {
        //objects
        private int _UserId;
        private string _Fullname = "";
        private string _Status = "";
        private int _isActive;
        private string _Username = "";

        public int UserId
        {
            get { return _UserId; }
            set { _UserId = value; }
        }
        public string Fullname
        {
            get { return _Fullname; }
            set { _Fullname = value; }
        }
        public string Status
        {
            get { return _Status; }
            set
            {
                if (_isActive == 1)
                {
                    _Status = "Active";
                }
                else
                {
                    _Status = "Not Active";
                }
            }
        }
        public string Username
        {
            get { return _Username; }
            set { _Username = value; }
        }

        public ObjectClass()
        {

        }
        //to store the objects inside list
        public List<ObjectClass> userDataSource()
        {
            SQLScripts SQL = new SQLScripts();
            DataTable dt = SQL.retrieveAllUsers();
            List<ObjectClass> lstOfUsers = new List<ObjectClass>();
            foreach (DataRow dr in dt.Rows)
            {
                ObjectClass oUser = new ObjectClass();
                oUser.UserId = Convert.ToInt32(dr["UserId"]);
                oUser.Username = Convert.ToString(dr["Username"]);
                oUser.Fullname = Convert.ToString(dr["Fullname"]);
                oUser._isActive = Convert.ToInt32(dr["IsActive"]);
                oUser.Status = oUser.Status;
                lstOfUsers.Add(oUser);
            }
            return lstOfUsers;
        }
    }

}

As you would notice, there is no 'Status' column in the table. We will set the value based on the IsActive value in the table and will be handled in the constructors.

Step 4
Now lets create another class to store our SQL scripts and name it s SQLScripts. This class will serve as the data access layer.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//add
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace aspxgridviewBlogDataBinding
{
    class SQLScripts
    {
        string conString = ConfigurationManager.ConnectionStrings["roCRM"].ConnectionString;

        public DataTable retrieveAllUsers()
        {
            SqlConnection sqlConn = new SqlConnection(conString);
            string sqlQuery = "SELECT * FROM dbo.sys_user";
            SqlCommand sqlComm = new SqlCommand(sqlQuery, sqlConn);
            SqlDataAdapter sqlDA = new SqlDataAdapter(sqlComm);
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            using (sqlConn)
            {
                sqlDA.SelectCommand = sqlComm;
                sqlDA.Fill(ds);
                dt = ds.Tables[0];
            }
            return dt;
        }
    }
}

Step 5
Now the last part, lets handle our code behind!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//add
using DevExpress.Web;

namespace aspxgridviewBlogDataBinding
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Grid_DataBinding(object sender, EventArgs e)
        {
            //cast sender as aspxgridview
            ASPxGridView grid = (ASPxGridView)sender;
           //to call ObjectClass.cs
            ObjectClass clsUser = new ObjectClass();
            grid.DataSource = clsUser.userDataSource();
        }

        protected void Grid_Init(object sender, EventArgs e)
        {
            ASPxGridView grid = (ASPxGridView)sender;
            grid.DataBind();
        }
    }
}

Now,build and run your program and you are good to go!

All The Best! :)

Monday, May 25, 2015

How to Bind ASPxComboBox to Object Class with MySQL Database

Assuming that you are using MySql as your database,lets say you have a combobox which values need to be obtained from the database.Something like below;
For this tutorial,i have the following table and its structure in the database. The name of my table is sys_country.
I will retrieve both CountryId, and CountryName and set CountryName as the visible items and the the CountryId as the value.

Step 1:
Add aspxComboBox to your aspx page either by manually typing it or dragging the controls from the toolbox.Its should be somewhere under DX.14.2 : Common Controls (my devEx version us 14.2.6).

Set the ID, and add the following properties to the tag.
- ValueField = Your object which later to be defined in your object class, as you can see from above, i set it as countryId, which is my object for the CountryId from my db. The countryId will be the value field for the selected items. Ex : when Malaysia is selected, it will return 1 as the value.
- TextField = The text to be displayed in the combobox.
-ValueType = The type of the value which in this tutorial, the countryId type which is Int.
-OnInit = In devExpress, it is a good approach to bind your controls in the OnInit event rather then binding it at page_load.You can read more about it at the devExpress page.

Step 2
Create a new class in your project that will store your objects and will be called by your code behind to get the list of countries set in the data object. This will serve as the Business Logic layer. In this tutorial i named it as CountryObject.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace myDevExBlog
{
    public class CountryObject
    {
        //objects
        private int _countryId;
        private string _countryName;

        public int countryId
        {
            get { return _countryId; }
            set { _countryId = value; }
        }
        public string countryName
        {
            get { return _countryName; }
            set { _countryName = value; }
        }

        public CountryObject()
        {

        }

        public List<CountryObject> getCountries()
        {
            //to store the list of countries
            List<CountryObject> lstCountries = new List<CountryObject>();
            //to call the mysqlscripts
            mysqlScripts clsMysqlScripts = new mysqlScripts();
            DataTable dt = clsMysqlScripts.retrieveCountries();
            foreach(DataRow dRow in dt.Rows)
            {
                //set data from datatable to objects
                CountryObject oCountry = new CountryObject();
                oCountry.countryId = Convert.ToInt32(dRow["CountryId"]);
                oCountry.countryName = dRow["CountryName"].ToString();
                lstCountries.Add(oCountry);
            }
            //retunr the list
            return lstCountries;
        }
    }
}

Step 3
Create another new class in your project that will handle your mysql scripts. This will serve as the Data Access Layer and will return datables.In this tutorial i named it as mysqlscripts.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using MySql.Data.MySqlClient;
using System.Configuration;

namespace myDevExBlog
{
    public class mysqlScripts
    {
        public DataTable retrieveCountries()
        {
            String mysqlConnStr = ConfigurationManager.ConnectionStrings["SWCS"].ConnectionString;
            MySqlConnection mysqlDbcon = new MySqlConnection(mysqlConnStr);
            String mysqlQuery = "SELECT CountryId, CountryName FROM sys_country";
            MySqlCommand mysqlComm = new MySqlCommand(mysqlQuery, mysqlDbcon);
            MySqlDataAdapter mysqlDA = new MySqlDataAdapter(mysqlComm);
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            try
            {
                mysqlDbcon.Open();
                mysqlDA.SelectCommand = mysqlComm;
                mysqlDA.Fill(ds);
                dt = ds.Tables[0];
            }
            catch (Exception ex)
            {
                mysqlDbcon.Close();
            }
            finally
            {
                mysqlDbcon.Close();
            }
            return dt;
        }
    }
}


Step 4
Now,for the last part, you can navigate back to your aspx code behind, and handle the OnInit event that was created earlier in Step 1:

protected void cbCountry_Init(object sender, EventArgs e)
        {
            CountryObject clsCountryObject = new CountryObject ();
            List<CountryObject > lstOfCountries = new List<CountryObject >();
            lstOfCountries = clsCountryObject.getCountries();
            cbCountry.DataSource = lstOfCountries;
            cbCountry.DataBind();
        }

Build and Run the project and you are good to go! :)