[GIS] How to get all fields of selected features in C#

arcgis-10.0arcobjectscfeatures

I am looking for a way to get all selected features from a map which belongs to a specific feature class (shapefile, geo database,…).

To be more specific and to give you a real case for my question: I want check if the feature class of selected feature has a special field. If this is the case I want to get the value of this field from the selected feature and add this value into a combobox. This process should be repeated for all selected features.

I tried the following but it crashed with an object reference error.

List<string> list = new List<string>();
IMap Pmap = doc.FocusMap;
IEnumFeature pEnumFeat = (IEnumFeature)Pmap.FeatureSelection;
pEnumFeat.Reset();
IFields fields;
try
{
  IFeature pfeat = pEnumFeat.Next();
  while (pfeat != null)
  {
    fields = pfeat.Fields;
    int x = fields.FindField("ID_K");
    if (!x.Equals(-1))
    {
      list.Add(pfeat.get_Value(x).ToString());
    }
    pfeat = pEnumFeat.Next();
    }
}
catch (Exception e)
{
  Console.WriteLine(e.Message);
}

UPDATE:

I've found a solution. Here is the working code:

List<string> list = new List<string>();
IMap Pmap = doc.FocusMap;
IEnumFeature pEnumFeat = (IEnumFeature)Pmap.FeatureSelection;
IFields fields;
pEnumFeat.Reset();
IEnumFeatureSetup enumFeatSetup = (IEnumFeatureSetup)pEnumFeat;
enumFeatSetup.AllFields = true;
try
{
   IFeature pfeat = pEnumFeat.Next();

   while (pfeat != null)
   {
      fields = pfeat.Fields;
      int x = fields.FindField("ID_K");
      list.Add(pfeat.get_Value(x).ToString());

      pfeat = pEnumFeat.Next();
    }
 }
 catch (Exception e)
 {
    Console.WriteLine(e.Message);
 }

These two line are especially important.

IEnumFeatureSetup enumFeatSetup = (IEnumFeatureSetup)pEnumFeat;
enumFeatSetup.AllFields = true;

If you don't use them you've only the shapefile included (default) and not the other fields and values.

Best Answer

Are you sure the value of the field isn't null? What about:

if (!x.Equals(-1))
{
  object value = pfeat.get_Value(x);
  list.Add(value == null ? null : value.ToString());
}

I'm not sure if you want to inline the null test, you could always do:

if (!x.Equals(-1))
{
  object value = pfeat.get_Value(x);
  if(value != null)
  {
    list.Add(value.ToString());
  }
  else
  {
    list.Add(null);
  }
}