如何从.NET应用程序更新.dbf文件

时间:2010-10-21 05:33:45

标签: c# .net asp.net dbf

我想从.net应用程序更新.dbf文件。 我能够将.dbf文件读入网格,但无法从我的.net应用程序更新.dbf文件。

我使用以下代码来读取.dbf文件。读书还可以。但是,无法更新.dbf文件。

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();
    }
}
}

注意:我还看到,第三方组件Apollo组件可用于从.NET应用程序读取,添加,编辑.dbf文件的记录。该组件由VistaSoftware.com开发。这不是免费软件。你能否确认,更新.dbf文件是否必须使用这个第三方组件,或者我可以通过我的.net应用程序来完成。

1 个答案:

答案 0 :(得分:5)

我会做这样的事情:

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;
}