Displaying the Default Value in databound controls on a web form when performing an Add

Displaying the Default Value in databound controls on a web form when performing an Add

Old forum URL: forums.lhotka.net/forums/t/334.aspx


mtavares posted on Friday, June 09, 2006

Hi,

I can't seem to find this answer anywhere, so maybe someone can help me.  I'm setting a default value for a smartdate in my business object within my DataPortal_Create Method.  I then expected that when I am putting my FormView of my web form into Insert Mode and I have a textbox bound to that field in my BO through a csla datasource, that the default date should be displayed within that textbox.  Is that the wrong assumption?  I've noticed that the same thing occurs in the Project Tracker Demo where a default date is set for the Project Object, but it is not displayed when putting the DetailsView in InsertMode.  Is there a way to fix this or is it something where I need to specifically assign the defaults to the controls?

Thanks,
Mike

mtavares replied on Monday, June 12, 2006

No one else has had this issue?  I would have thought it was a common question.  I've done some more digging, and it seems that the DataItem object on a DetailsView or FormView is nothing when the controls are in InsertMode.  What I don't know is if this is a function of those controls or of the CslaDatasource control (Or ObjectDatasource for that matter since it does the same thing). 

I can live with setting the Default Values in each control's databound event, but it just seems to defeat the purpose of setting them in the business object.  If someone could weigh in on this as to what the best practice is, or if there is a way of actually getting that DataItem object to be set, I'd greatly appreciate it.

Thanks,
Mike

ajj3085 replied on Monday, June 12, 2006

I would think the date should display.  Can you post some relevent code?

mtavares replied on Monday, June 12, 2006

Here's the code for the CslaDatasource:

Protected Sub CslaDataSource2_InsertObject(ByVal sender As Object, ByVal e As Csla.Web.InsertObjectArgs) Handles CslaDataSource2.InsertObject

   Dim obj As NdrnGender = GetNdrnGender()

   Csla.Data.DataMapper.Map(e.Values, obj, New String() {"NDRNGenderID", "NDRNTimeStamp"})

   e.RowsAffected = SaveNdrnGender(obj)

End Sub

Protected Sub CslaDataSource2_SelectObject(ByVal sender As Object, ByVal e As Csla.Web.SelectObjectArgs) Handles CslaDataSource2.SelectObject

   Try

      Dim Obj As Object = GetNdrnGender()

      If Obj IsNot Nothing Then

         e.BusinessObject = Obj

      End If

   Catch ex As System.Security.SecurityException

      ValidationUtil.ApplyValidationToValidator(Master.FindControl("vldGeneral"), ex)

      ChangeView(Views.MainView)

   End Try

End Sub

Here's the code for the GetNdrnGender function:

Private Function GetNdrnGender() As NdrnGender

   Dim BusnessObject As Object = Session("currentObject")

   If BusnessObject Is Nothing OrElse Not TypeOf BusnessObject Is NdrnGender Then

      If MainFormView.CurrentMode = FormViewMode.Edit Then

         BusnessObject = NdrnGender.GetNdrnGender(Me.LookupGridView.SelectedValue, Profile.TimeZone)

      Else

      BusnessObject = NdrnGender.NewNdrnGender(Profile.TimeZone)

   End If

   Session("currentObject") = BusnessObject

End If

Return CType(BusnessObject, NdrnGender)

And here's the code in the dataportal_Create method that defaults the date:

<CSLA.RunLocal()> _

Protected Overloads Sub DataPortal_Create(ByVal crit as TimeZoneCriteria)

' Set defaults for properties

   m_activeDate = New SmartDate(TimeZoneSource.TZSClass.ConvertUtcToLocal(crit.TimeZone, Date.UtcNow))

   m_timeZone = crit.TimeZone

   Me.ValidationRules.CheckRules()

End Sub

When I stepped through debugging, the Default values for the date and timezone are being set properly, but those default values never get set to the textbox in the FormView control that is bound to the ActiveDate Property in the BO.  If more code is needed, let me know and I'll be happy to provide it, but these are the areas where the the defaults should be set from.

Thanks,

Mike

zglenn replied on Thursday, August 24, 2006

I am having the same issue. Setting default values in my DataPortal_Create sub in my aspx.vb class the object contians the correct values but they are never set in the insertitemtemplate controls. SelectObject is never called when debugging? thanks, Zac

david.wendelken replied on Friday, August 25, 2006

I **think** that the SelectObject is called for the grid as a whole, not for a given row.

(I'm still learning, and that is what appears to be happening based on my work over the last few days.  Haven't had time to work thru an experiment to prove my suspicion yet.)

I'm not sure whether forcing a databind on the grid would do anything useful or not.

david.wendelken replied on Friday, August 25, 2006

Just read in a different thread that there's a command to "reset bindings" that might be applicable here...

RockfordLhotka replied on Friday, August 25, 2006

The answer is to use the DetailsView.ItemCreated event. Handle this in your page and set the default values directly into the controls within your DetailsView.

I still think that this was an oversight by the ASP.NET team - as this is obviously a very awkward solution - but it appears to be the correct one...

  Protected Sub DetailsView1_ItemCreated( _
    ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles DetailsView1.ItemCreated

    If DetailsView1.DefaultMode = DetailsViewMode.Insert Then
      Dim obj As Project = GetProject()

      CType(DetailsView1.Rows(1).Cells(1).Controls(0), TextBox).Text = obj.Name
      CType(DetailsView1.Rows(2).Cells(1).Controls(0), TextBox).Text = obj.Started
      CType(DetailsView1.Rows(3).Cells(1).Controls(0), TextBox).Text = obj.Ended
      CType(DetailsView1.FindControl("TextBox1"), _
        System.Web.UI.WebControls.TextBox).Text = obj.Description
    End If

  End Sub

dlcollison replied on Wednesday, August 30, 2006

Attempted to take your code and get it to work within a FormView as follows - any ideas on how I can set textbox values or checkbox values to default values:

 

Protected Sub frmPlants_ItemCreated(ByVal sender As Object, ByVal e As System.EventArgs) Handles frmPlants.ItemCreated

   If (Me.frmPlants.CurrentMode = FormViewMode.Insert) Then

      CType(frmPlants.FindControl("logIsActive"), TextBox).Text = 1

      CType(frmPlants.FindControl("corporation_id"), TextBox).Text = Session("svCorpId")

   End If

End Sub

System bombs when I run the code - getting the following message:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an
instance of an object.

 

Any assistance will be appreciated.

   DC

xal replied on Wednesday, August 30, 2006

I might be just stating the obvious, but if FindControl doesn't find a control by that name, it will return null, and casting that to whatever or accessing a property, will throw a null reference exception.
Can you check that your Find control is actually returning anything?
Perhaps you mistyped the control's name...

Andrés

av_harris replied on Thursday, July 12, 2007

For anyone (like me) still struggling with this issue. I just discovered that the error is being thrown because the form must be in edit mode before a textbox value can be set. I'm stil experimenting but I guess you could set the mode to edit, set your values, then change it back to insert again.

I'm trying to figure out how to bring back entered values in a form after a rules violation during insert. I got it working in the ItemCreated event but still haven't figured out how I will initiate this event during the insert process.

If someone has developed a good process for performing validation, I'd really appreciate a little guidance here.

dinparacha replied on Thursday, October 30, 2008

Due to some reasons the frmPlants_ItemCreated(..) is being called more then once while loading the page. In the first call it does not find the control but in the subsequent calls it find it and sets the defualt value even if it is in insert mode. So  just add one 'if' statement before setting the default value

 

corporation_id as TextBox=frmPlants.FindControl("corporation_id")

if (corporation_id!=null) then

corporation_id.Text=Session("svCorpId")

end if

RockfordLhotka replied on Thursday, October 30, 2008

Getting default data into a grid or details view in insert mode is a pain. Microsoft really didn't think this scenario through very well. Look at PTWeb, because ProjectEdit.aspx does address this with code such as:

  protected void DetailsView1_ItemCreated(object sender, EventArgs e)
  {
    if (DetailsView1.DefaultMode == DetailsViewMode.Insert)
    {
      Project obj = GetProject();
      ((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text = obj.Name;
      ((TextBox)DetailsView1.Rows[2].Cells[1].Controls[0]).Text = obj.Started;
      ((TextBox)DetailsView1.Rows[3].Cells[1].Controls[0]).Text = obj.Ended;
      ((TextBox)DetailsView1.FindControl("TextBox1")).Text = obj.Description;
    }
  }

aboundweb replied on Tuesday, September 11, 2007

Hey there,

This is Joe from Abound Inc.  I spent some time on this issue and found the simple solution.  You simply need to create a template field for the field you want to set a default value for.  In the template field ASP.Net is very flexible in that you can put any type of control in there whether it be a label, text box, checkbox etc...  You set the value for that template field by making a call to a method you create in the code-behind file.  I have a page called Clients.aspx where I have a gridview and detailsview.  In this page I set it up so that when the user clicks to add a new client, the COMPANY_ID field is set to session variable and cannot be changed by the user.

In the Clients.aspx file the code for the template field looks like this:

<asp:TemplateField HeaderText="COMPANY_ID" SortExpression="COMPANY_ID">
                <EditItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("COMPANY_ID") %>'></asp:Label>
                </EditItemTemplate>
                <InsertItemTemplate>
                    &nbsp;
                    <asp:Label ID="Label2" runat="server" Text='<%# GetCompanyID() %>'></asp:Label>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("COMPANY_ID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

Notice the call to GetCompanyID() in the InsertItemTemplate.  That method is defined in the code-behind file (Clients.aspx.cs):

protected String GetCompanyID()
    {
        String sCompany = "";
        if (Session["company_id"] != null)
        {
            sCompany = (string)Session["company_id"];
        }
        else
        {
            sCompany = "0";
        }
        return sCompany;
    }

I hope this helps

Joe Werner
Abound Inc.
www.aboundweb.com

Copyright (c) Marimer LLC