1. 程式人生 > >在DataGridView中瀏覽shp圖層的屬性表[.dbf檔案]

在DataGridView中瀏覽shp圖層的屬性表[.dbf檔案]

OpenFileDialog ofdDBF =new OpenFileDialog();
ofdDBF.Filter 
="屬性表文件(*.dbf)|*.dbf";
if (ofdDBF.ShowDialog() == DialogResult.OK)
{
    
string OpenFileName = ofdDBF.FileName.Trim();
    
string dbfFilePath = Path.GetDirectoryName(OpenFileName);
    
string dbfFileName = Path.GetFileName(OpenFileName);

    IWorkspaceFactory pWorkspaceFactory 
=new ShapefileWorkspaceFactoryClass();
    IWorkspace pWorkspace 
= pWorkspaceFactory.OpenFromFile(dbfFilePath, 0);
    IFeatureWorkspace pFeatureWorkspace 
= pWorkspace as IFeatureWorkspace;
    
if (pFeatureWorkspace !=null)
    {
        IFeatureClass pFeatureClass 
= pFeatureWorkspace.OpenFeatureClass(dbfFileName);
        
if (pFeatureClass !=null)
        {
            DataTable dt 
=new DataTable();
            DataColumn dc 
=null;

            
for (int i =0; i < pFeatureClass.Fields.FieldCount; i++)
            {
                dc 
=new DataColumn(pFeatureClass.Fields.get_Field(i).Name);
                dt.Columns.Add(dc);
            }

            IFeatureCursor pFeatureCursor 
= pFeatureClass.Search(nullfalse);
            IFeature pFeature 
= pFeatureCursor.NextFeature();
            DataRow dr 
=null;
            
while (pFeature !=null)
            {
                dr 
= dt.NewRow();
                
for (int j =0; j < pFeatureClass.Fields.FieldCount; j++)
                {
                    
if (pFeatureClass.FindField(pFeatureClass.ShapeFieldName) == j)
                    {
                        dr[j] 
= pFeatureClass.ShapeType.ToString();
                    }
                    
else
                    {
                        dr[j] 
= pFeature.get_Value(j).ToString();
                    }
                }
                dt.Rows.Add(dr);
                pFeature 
= pFeatureCursor.NextFeature();
            }
            dataGridView1.DataSource 
= dt;
        }
    }
}

這樣就再也不用每次都費力的開啟ArcMap了,用這個小工具即可。