I want to update a .dbf file from my .net application. I was able to read the .dbf file into a grid but not able to update the .dbf file from my .net application.
I have used following code to read the .dbf file. Reading is okay. But, not able to update .dbf file.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Odbc;
namespace DBFwin
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ConnectToDBF()
{
System.Data.Odbc.OdbcConnection oConn = new System.Data.Odbc.OdbcConnection();
oConn.ConnectionString = @"Driver={Microsoft dBase Driver (*.dbf)};SourceType=DBF;SourceDB=D:\databases\;Exclusive=No; Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
oConn.Open();
System.Data.Odbc.OdbcCommand oCmd = oConn.CreateCommand();
//Test.DBF is the dbf file which is located at C:\rd\Setup folder.
oCmd.CommandText = @"SELECT * FROM C:\rd\Setup\Test.DBF";
DataTable dt = new DataTable();
dt.Load(oCmd.ExecuteReader());
//Adding a row..
//DataRow dtRow = dt.LoadDataRow();
DataRow dtRow = dt.NewRow();
//FIELD1 and FIELD2 are two columns of dbf file.
dtRow["FIELD1"] = 999;
dtRow["FIELD2"] = "RA-12";
dt.BeginLoadData();
dt.Rows.Add(dtRow);
dt.EndLoadData();
//Above code adding a row in the grid, which is fine.
//How can i update dbf file from this source code???
oConn.Close();
dataGridView1.DataSource = dt;
}
private void 开发者_如何学编程btnClick_Click(object sender, EventArgs e)
{
ConnectToDBF();
}
}
}
NOTE: I have also seen that, a third party component Apollo component is availble to read, add, edit records of .dbf file from .NET application. This component is developed by VistaSoftware.com. This not a freeware. Could you please confirm, to update .dbf file whether i have to use this third party component or i can do it by my .net application.
I would do something like this :
private void ConnectToDBF()
{
System.Data.Odbc.OdbcConnection oConn = new System.Data.Odbc.OdbcConnection();
oConn.ConnectionString = @"Driver={Microsoft dBase Driver (*.dbf)};SourceType=DBF;SourceDB=D:\databases\;Exclusive=No; Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
oConn.Open();
System.Data.Odbc.OdbcCommand oCmd = oConn.CreateCommand();
// Insert the row
oCmd.CommandText = @"INSERT INTO C:\rd\Setup\Test.DBF VALUES(999, 'RA-12')";
oCmd.ExecuteNonQuery();
// Read the table
oCmd.CommandText = @"SELECT * FROM C:\rd\Setup\Test.DBF";
DataTable dt = new DataTable();
dt.Load(oCmd.ExecuteReader());
oConn.Close();
dataGridView1.DataSource = dt;
}
精彩评论