How to import excel and foxpro (.dbf) files into Datagrid using c #?
Hello All,
I am new to the site and the C# language as well. I am trying to find out how I can import data into my Grid using C sharp. I was able to import Foxpro dbf's now I want to import excel files. Rather than only filtering DBF's I also added .XLS's whcich you will see in the code. Unfortunately, I am getting a not known or unknow Driver error, which ofcourse is the connection string for DBF's and not excel. I'm trying to set it up such that u can choose either DBF or excel. Here is the code for this particualr form.
Thanks for your help, it is much appreciated.
CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.Odbc;
namespace MySQLData
{
public partial class Form7 : Form
{
public Form7()
{
InitializeComponent();
}
private void BrowseButton_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.Title = "Select a DBF or XLS file";
file.InitialDirectory = @" c:\gsc\";
file.FileName = txtFilename.Text;
file.Filter = "Excel Sheet(*.xls)|*.xls|DBF Files(*.dbf)|*.dbf";
file.FilterIndex = 100;
file.RestoreDirectory = true;
if (file.ShowDialog() == DialogResult.OK)
{
txtFilename.Text = file.FileName; //Filename and Path
Application.DoEvents();
}
}
public static DataTable GetDataTableDBF(string strFileName)
{
OdbcConnection conn = new OdbcConnection("Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=" + Path.GetFullPath(strFileName).Replace(Path.GetFileName(strFileName), "") + ";Exclusive=No");
conn.Open();
string strQuery = "SELECT * FROM [" + Path.GetFileName(strFileName) + "]";
OdbcDataAdapter adapter = new OdbcDataAdapter(strQuery, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds.Tables[0];
}
private void ViewButton_Click_1(object sender, EventArgs e)
{
try
{
DataTable dt = GetDataTableDBF(txtFilename.Text);
dataGridView1.DataSource = dt.DefaultView;
label1.Text = "Click [BROWSE] to select and view another file.";
label2.Text = "Total records: [" + dt.Rows.Count + "]";
MessageBox.Show("Total records imported [" + dt.Rows.Count + "]");
}
catch (Exception ex)
{
MessageBox.Show("An error has occured. Please click browse and select a file to view. " + ex.Message);
}
}
private void MainMenuButton_Click(object sender, EventArgs e)
{
Form4 Form4 = new Form4();
Form4.Show();
this.Hide();
}
}
}