Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to read file dbf into datagridview

C#
private void button1_Click(object sender, EventArgs e)
        {

            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Title = "Select file";
            fdlg.InitialDirectory = @"E:\0.Project\Combine\S230201C31C4UnZip";
            fdlg.Filter = "DBF Files(*.dbf)|*.dbf|All Files(*.*)|*.*";
            fdlg.FilterIndex = 1;
            fdlg.RestoreDirectory = true;
            if (fdlg.ShowDialog() == DialogResult.OK)
            {
                Import(fdlg.FileName);

                Application.DoEvents();
            }
        }

void Import(string filename)
        {
            DataTable dt = GetDataTableDBF(filename);
            dataGridView1.DataSource = dt.DefaultView;
        }

        DataTable GetDataTableDBF(string str)
        {

            OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path.GetFullPath(str).Replace(System.IO.Path.GetFileName(str), "") + ";Extended Properties=dBASE IV;User ID=Admin;Password=;");

            conn.Open();

            string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(str) + "]";

            OleDbDataAdapter adapter = new OleDbDataAdapter(strQuery, conn);

            DataSet ds = new DataSet();
            adapter.Fill(ds);

            return ds.Tables[0];

        }
Posted
Updated 3-Mar-15 18:29pm
v2
Comments
Tomas Takac 4-Mar-15 1:29am    
And the problem is?
Ton162 4-Mar-15 1:43am    
my code is error, can you help me?

1 solution

Try this


using System.Data.OleDb; 
        private void ImportDBF_Load(object sender, EventArgs e) 
        { 
            if (ofdDBF.ShowDialog()==DialogResult.OK) 
            { 
                string connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ofdDBF.FileName.Substring(0, ofdDBF.FileName.LastIndexOf("\\")) + ";Extended Properties=dBASE IV;"; 
 
                OleDbConnection conn = new OleDbConnection(connStr); 
                conn.Open(); 
 
                string cmd_string = "select * from " + ofdDBF.SafeFileName.Substring(0, ofdDBF.SafeFileName.IndexOf(".")); 
                MessageBox.Show(cmd_string); 
                OleDbDataAdapter da = new OleDbDataAdapter(cmd_string, conn); 
                DataSet ds = new DataSet(); 
                da.Fill(ds); 
                dgvImport.DataSource = ds.Tables[0]; 
 
            } 
 
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900