Monday, 20 February 2012

Import from Excel to Data Table - C# Code

 System.Windows.Forms.OpenFileDialog oFileDialog = new System.Windows.Forms.OpenFileDialog();
            oFileDialog.Filter = "Excel (*.xls;*.xlsx;*)|*.xls;*.xlsx;*";

            oFileDialog.ShowDialog();

            string strpath = oFileDialog.FileName;

            //string strpath = @"C:\Users\shihafathw\Desktop\Employees.xls";
            OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + strpath + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");

            OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);

            DataTable dt = new DataTable();

            da.Fill(dt);

Adding Item to the beginning of List

Class Name =  UserType
--------------------------------------

 public UserType(int id, string type)
        {
            this.Type= type;
            this.id = id;
        }

public int ID{ get; set; }
public string Type{ get; set; }
--------------------------------------
 Method ;
 public static List<UserType> GetUserType()
        {
            List<UserType> userType = new List<UserType>();
            userType.Add(new UserType(1, "Admin"));
            userType.Add(new UserType(2, "Employee"));
            userType.Add(new UserType(3, "Visitor"));
            return userType;
        }
 -------------------------------------------------------------------------------------------

From GUI

 List<UserType> userTypeList = UserType.GetUserType();
           
            userTypeList.Insert(0,new UserType(-1, "Select"));

            cmbUserType.ItemsSource = userTypeList;
            cmbUserType.DisplayMemberPath = "Type";
            cmbUserType.SelectedValuePath = "ID";

            cmbUserType.SelectedIndex = 0;

Note :
Use the Insert method: