Check for read-only or hidden fields in DetailsView that are not in the DataKey collection.

protected void DetailsView1_PreRender(object sender, System.EventArgs e)
{
 try {
  //Catch error when an old .NET Framework doesn't have a DetailsView.DataSourceObject available.
  object FrameworkErrorCatcher = sender.DataSourceObject;
 } catch {
  return;
 }
 if (sender.DataSourceObject is ObjectDataSource) {
  ObjectDataSource DetailsViewDataSource = sender.DataSourceObject;
  string SourceUpdateMethodName = DetailsViewDataSource.UpdateMethod;
  if (string.IsNullOrEmpty(SourceUpdateMethodName) == false) {
   foreach (DataControlField DetailsViewDataControlField in sender.Fields) {
    if (DetailsViewDataControlField is BoundField) {
     BoundField DetailsViewBoundField = DetailsViewDataControlField;
     string FieldName = DetailsViewBoundField.DataField;
     if (DetailsViewBoundField.ReadOnly == true | DetailsViewBoundField.Visible == false) {
      int DataKeyIndex = Array.IndexOf(sender.DataKeyNames, FieldName);
      if (DataKeyIndex == -1) {
       throw new ApplicationException(string.Format("Read-only or hidden field {0} is not in the {1} DateKey collection.  This field will not be returned during updates.", FieldName, sender.ID));
      }
     }
    }
   }
  }
 }
}

No comments:

Post a Comment