вторник, 3 апреля 2012 г.

Migrating from Visual Fox Pro to Sql Server. (Converting dbf to MS Sql Server etc) Second edition. Creating dbf file and editing data.

    Here is the example how we can easy create and edit data in our dbf file.  This dll was the basis for my "Dbf2Any" programm. Wich can convert dbf files to MS Sql Server, PostgreSql. At this moment at the work converting dbf to Oracle and MySql.
Here we will be using datagrid in virtual mode.
I think that this example is clear enough,  but if anyone will have questions please write me.


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



string[] Fields = new string[] { "Fld1", "Fld2", "Fld3", "Fld4", "Fld5",
                                    "Fld6", "Fld7","Fld8", "Fld9", "Fld10" };


List<DbFieldInfo> fieldsList = new List<DbFieldInfo>();
    DbfRecordset _recSet;

    string fileName = Application.StartupPath + "\\test.dbf";


 private void OpenCreateRecordSet()
    {
      if (System.IO.File.Exists(fileName))
      {
        _recSet = new DbfRecordset(fileName);
        for (int i = 0; i < _recSet.FieldCount; i++)
        {
          this.dataGridView1.Columns.Add(_recSet.Fields[i].Name, _recSet.Fields[i].Name + " Type(" + _recSet.Fields[i].Type + ")");
        }
      }
      else
      {
        for (int i = 0; i < 10; i++)
        {
          DbFieldInfo dbFldInfo = new DbFieldInfo(Fields[i], 'C', 20);
          fieldsList.Add(dbFldInfo);
        }
        _recSet = DbfRecordset.Create(fileName, fieldsList);
      }
    }


private void SetupGrid()
    {
      if (_recSet == null)
      {
        return;
      }

      this.dataGridView1.RowCount = _recSet.RecordCount;
      this.dataGridView1.CellValueNeeded += new DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);    
      this.dataGridView1.CellValuePushed += new DataGridViewCellValueEventHandler(dataGridView1_CellValuePushed);
      this.dataGridView1.NewRowNeeded += new DataGridViewRowEventHandler(dataGridView1_NewRowNeeded);
    }


 void dataGridView1_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
    {
      _recSet.Move(e.RowIndex + 1);
      _recSet.Edit();
      _recSet[e.ColumnIndex + 1] = e.Value;
      _recSet.Update();
    }

    void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
    {
      _recSet.Move(e.RowIndex + 1);
      if (_recSet.Fields[e.ColumnIndex].Type == 'C')
      {
        e.Value = _recSet[e.ColumnIndex + 1].ToString().Trim();
      }
      else
      {
        e.Value = _recSet[e.ColumnIndex  + 1];
      }
    }


 private void btnAddRecord_Click(object sender, EventArgs e)
    {
      _recSet.AddNew();
      _recSet.Update();
      this.dataGridView1.RowCount = _recSet.RecordCount;
    }





Комментариев нет:

Отправить комментарий