Friday, July 23, 2010

Import .dbf data to gridview and SQL

In this example am explaining how to insert a .dbf file into a Gridview and to a database table..

To perform this you need to design a table with the structure similar to your .dbf file.

using System;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Data.OleDb;

using System.Data.Odbc;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

System.Data.Odbc.OdbcConnection oConn = new System.Data.Odbc.OdbcConnection();

Con.ConnectionString = @"Driver={Microsoft dBase Driver (*.dbf)};SourceType=DBF;SourceDB=D:\Sample\;Exclusive=No; Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";

Con.Open();

System.Data.Odbc.OdbcCommand oCmd = oConn.CreateCommand();

oCmd.CommandText = @"SELECT * FROM D:\Sample\IndiaDB\FileName.dbf";

DataTable dat = new DataTable();

dat.Load(oCmd.ExecuteReader());

Con.Close();

GridView1.DataSource = dat;

GridView1.DataBind();

}

}

With this your .dbf file data will be imported to the Gridview. Lets see the code for doing the same to a table..

using System;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Data.OleDb;

using System.Data.Odbc;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString);

protected void Page_Load(object sender, EventArgs e)

{

DataTableReader reader = dt.CreateDataReader();

conn.Open(); ///this is my connection to the sql server

SqlBulkCopy sqlcpy = new SqlBulkCopy(conn);

sqlcpy.DestinationTableName = "YourTable"; //copy the datatable to the sql table

sqlcpy.WriteToServer(dt);

conn.Close();

}

}

And now your .dbf data can be imported to both Gridview and SQL table.