在DataGridView中浏览shp图层的属性表[.dbf文件]
每次浏览shp图层的属性表时,总是使用ArcMap打开,比较麻烦。虽然网络中有小巧的DBF数据库浏览工具,也还是觉得有点大材小用。
下面的C#代码用来读取shp图层的属性表,并在DataGridView中显示,在VS 2005中调试通过,代码很简单。
下面的C#代码用来读取shp图层的属性表,并在DataGridView中显示,在VS 2005中调试通过,代码很简单。
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(null, false);
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了,用这个小工具即可。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(null, false);
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;
}
}
}