Import Data from FoxPro (DBF) database to DataGridView in C#

First add a browser control,TextBox,Button and a DataGridView Control on form

Form1.JPG

Add the following code in Button Click Event

        private void button1_Click_1(object sender, EventArgs e)

        {

            OpenFileDialog fdlg = new OpenFileDialog();

            fdlg.Title = "Select file";

            fdlg.InitialDirectory = @"c:\";

            fdlg.FileName = txtFileName.Text;

            fdlg.Filter = "DBF Files(*.dbf)|*.dbf|All Files(*.*)|*.*";

            fdlg.FilterIndex = 1;

            fdlg.RestoreDirectory = true;

            if (fdlg.ShowDialog() == DialogResult.OK)

            {

                txtFileName.Text = fdlg.FileName;

                Import();

                Application.DoEvents();

            }

        }


Form2.JPG

When you select any DBF file from Browser page then you get the full path of dbf file.

You will pass this path in the following function that will return the dbf file data in a dataset.

        public static DataTable GetDataTableDBF(string strFileName)

        {

            System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection("Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=" + System.IO.Path.GetFullPath(strFileName).Replace(System.IO.Path.GetFileName(strFileName), "") + ";Exclusive=No");

            conn.Open();

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

            System.Data.Odbc.OdbcDataAdapter adapter = new System.Data.Odbc.OdbcDataAdapter(strQuery, conn);

            System.Data.DataSet ds = new System.Data.DataSet();

            adapter.Fill(ds);

            return ds.Tables[0];

        }


You can easily show dataset data in Datagridview.

DataTable
dt = GetDataTableDBF(txtFileName.Text);
dataGridView1.DataSource = dt.DefaultView;

Form3.JPG

Up Next
    Ebook Download
    View all
    Learn
    View all