Search code examples
c#ms-accessfieldcaption

Add caption to access fields with c#


I used this code for create an access database.

public void CreateAccessAssetFile(string DataSourcePath, string fileName)
{
    if (File.Exists(DataSourcePath + fileName))
            File.Delete(DataSourcePath + fileName);

    //Create Database
    string cnnStr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" 
                   + DataSourcePath + fileName + "; Jet OLEDB:Engine Type=5";
    var catType = Type.GetTypeFromProgID("ADOX.Catalog");
    object o = Activator.CreateInstance(catType);
    catType.InvokeMember("Create", 
                         BindingFlags.InvokeMethod, 
                         null, 
                         o, 
                         new object[] { cnnStr });

    OleDbConnection cnn = new OleDbConnection(cnnStr);
    cnn.Open();
    var cmd = cnn.CreateCommand();
    cmd.CommandText = "CREATE TABLE TblInfoCompany (fn TEXT , ln TEXT)";
    cmd.ExecuteNonQuery();
}

Now I want to add caption to two fields that when we open the access file,the first field be "FirstName" and second field be "LastName".

How Can I do this?

Thanks.


Solution

  • Caption has no relevance outside of MS Access, however, here are some notes using interop:

     using Microsoft.Office.Interop.Access.Dao;
    
    
            DBEngine dbEng = new DBEngine();
            Workspace ws = dbEng.CreateWorkspace("", "admin", "",
                WorkspaceTypeEnum.dbUseJet);
            Database db = ws.OpenDatabase(@"z:\docs\test.accdb", false, false, "");
            TableDef tdf = db.TableDefs["Table1"];
            Field fld = tdf.Fields["Field1"];
    
            Property prp = fld.CreateProperty("Caption", 10, "My caption");
    
            fld.Properties.Append(prp);