locked
Prepopulate fields with default values RRS feed

  • Question

  • User-1240450359 posted

    Hi,

    I need to prepopulate some of the fields of the insert template with default values?

    Fields like StandardDelivery = 12.50;    or

    DateCreated = DateTime.Now;  this should now be readonly

    Can you tell me where this logic should go

    Thanks, Andrew

    Monday, January 14, 2008 10:02 AM

Answers

  • User-69253881 posted

    David, i just not found your second proposal (attribute named as DefaultValue) - may be it in next issue. I did it by your first variant. So i show it for everyone who tries to do the same (makes your own DynamicDataField for insert method when we want to set up different default values by Attribute named as Description):

    look at the code of our new Text_Insert.ascx and Implementation of default value for Category table(for example) for CategoryName filed ,

    at first the control Text_Insert.ascx:

     html:

    <%@ Control Language="C#" CodeFile="Text_Insert.ascx.cs" Inherits="Text_InsertField" %>
    <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ID="reqName" ControlToValidate="TextBox1" Display="Dynamic" Enabled="false" />
    <asp:DynamicValidator runat="server" ID="dynamicValidator" ControlToValidate="TextBox1" Display="Dynamic" />
    <asp:RegularExpressionValidator runat="server" ID="regexValidator" ControlToValidate="TextBox1" Display="Dynamic" Enabled="false" />

      code behind:

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Xml.Linq;
    using System.Web.DynamicData;

    public partial class Text_InsertField : FieldTemplateUserControlBase {
        protected void Page_Load(object sender, EventArgs e) {
            TextBox1.MaxLength = MetaMember.MaxLength;
            if (MetaMember.MaxLength < 20)
                TextBox1.Columns = MetaMember.MaxLength;
                TextBox1.ToolTip = MetaMember.Description;
                TextBox1.Text = MetaMember.Description;

            SetupRequiredFieldValidator(reqName);
            SetupRegexValidator(regexValidator);
            SetupDynamicValidator(dynamicValidator);
            
        }
        
        protected override void ExtractValues(IOrderedDictionary dictionary) {
            if (TextBox1.Text != "")
            {
                dictionary[DataField] = ConvertEditedValue(TextBox1.Text);
            }
        }
    }

     

     


    Now look at the category.cs file with the Category class:

     

    using System;
    using System.Data;
    using System.Configuration;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Web.DynamicData;
    /// <summary>
    /// Summary description for Category
    /// </summary>

    [ImageFormat("Picture", 100, 100)]
    [RenderHint("Picture", "DbImage")]
    [RenderHint("CategoryName", "Text")] // we set up renderhint control
    [Description("CategoryName", "TEST")] // we setup default value by Description attribute
    public partial class Category
    {

    }

      

    Finally we will find that when we press button new in detailsview control we will get prerendered value equals "TEST" for CategoryName field. So now we can reuse our Text_Insert.ascx module much times from many table's objects, we will need only to point pairs of attributes when we will partial classes by only two lines:

     

    [RenderHint("OrderName", "Text")]     // we set up renderhint control
    [Description("OrderName", "New...")] // we setup default value by Description attribute


    Sincerely, LukCAD

    PS: You can repeat this code if you will try expand by yourself this code from this placement(10,2 Mb): download

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 15, 2008 4:43 PM

All replies

  • User1641955678 posted

    Hi Andrew,

    This sounds like essentially the same question as your other post.  Or is it?

    thanks,
    David

    Monday, January 14, 2008 2:24 PM
  • User-69253881 posted

    Hi Andrew. You need use DynamicDataFields, where you must place code for INSERT event into file named like this one: YOUDATAFIELDCONTROL_INSERT.

    Look at the codes from three files that i wrote for example, may be it will more clear. The names files are next:

    - DateAjax.ascx

    - DateAjax_Edit.ascx

    - DateAjax_Insert.ascx 

     Code of  DateAjax.ascx:

     

    <%@ Control Language="C#" Inherits="System.Web.DynamicData.FieldTemplateUserControlBase" %>
    <script runat="server">
    </script>
    <%# string.Format("{0:d}", DataValue)%>
     
     

    Code of DateAjax_Edit.ascx:

      

    <%@ Control Language="C#" Inherits="System.Web.DynamicData.FieldTemplateUserControlBase" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e) {
            TextBox1.ToolTip = MetaMember.Description;
            SetupRequiredFieldValidator(reqName);
            SetupDynamicValidator(dynamicValidator);
        }
        protected override void ExtractValues(IOrderedDictionary dictionary) {
            if (TextBox1.Text == "")
            {
                TextBox1.Text = DateTime.Today.Date.ToString();
            }
            dictionary[DataField] = ConvertEditedValue(TextBox1.Text);
        }
    </script>
    <asp:TextBox ID="TextBox1" runat="server" Text='<%# string.Format("{0:d}", DataValue) %>' Columns="20"></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ID="reqName" ControlToValidate="TextBox1" Display="Dynamic" Enabled="false" />
    <asp:DynamicValidator runat="server" ID="dynamicValidator" ControlToValidate="TextBox1" Display="Dynamic" />
    <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server"
    TargetControlID="TextBox1"
    Format="dd.MM.yyyy"
    >
    </ajaxToolkit:CalendarExtender>

     

    Code of  DateAjax_Insert.ascx:

      

    <%@ Control Language="C#" Inherits="System.Web.DynamicData.FieldTemplateUserControlBase" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e) {
            TextBox1.ToolTip = MetaMember.Description;
            SetupRequiredFieldValidator(reqName);
            SetupDynamicValidator(dynamicValidator);
        }
        protected override void ExtractValues(IOrderedDictionary dictionary) {
            dictionary[DataField] = ConvertEditedValue(TextBox1.Text);
        }
    </script>
    <asp:TextBox ID="TextBox1" runat="server" Text='<%# string.Format("{0:d}", DateTime.Today) %>' Columns="20"></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ID="reqName" ControlToValidate="TextBox1" Display="Dynamic" Enabled="false" />
    <asp:DynamicValidator runat="server" ID="dynamicValidator" ControlToValidate="TextBox1" Display="Dynamic" />
    <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server"
    TargetControlID="TextBox1"
    Format="dd.MM.yyyy"
    >
    </ajaxToolkit:CalendarExtender>

     

    To use that controls into your project you must map it by by RenderHint Attribute for the partial class of your needing table object. You can do it by creating cs file in App_Code folder of your web project for example.

    Please, look at the example of this code:

     

    using System;
    using System.Data;
    using System.Configuration;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Web.DynamicData;
    [RenderHint("Date", "DateAjax")]  // This is your implementation of behavior when the select or edit or insert method will works by RenderHint Attribute
    [RenderHint("Filename", "FileImage")]
    [ImageUrl("Filename", "~/images/{0}")]
    [ImageFormat("Filename", 100, 100)]
    [ImageEnabled("Filename", "jpg,gif,png,bmp,tif")]
    public partial class FilePicture
    {
    }

      You can download project and find it there to execute it by VS2008 Express.

    Sincerely, LukCAD 

    Monday, January 14, 2008 5:47 PM
  • User-1240450359 posted

    Hi David,

    More or less the same, this post is wanting the values to be populated when the edit button is pressed and the other post is wanting the values calculated after the update or insert buttons are pressed.

    The default values in question are already in the sql database schema for each field, i.e. in the [Default value or binding] setting. These values do not seem to be pulled across, so I need a way of manually setting these values.

     Thanks, Andrew 

    Tuesday, January 15, 2008 9:35 AM
  • User-1240450359 posted

    Hi LukCAD,

    Thanks for your response, it's really helped in a couple of ways, but it's not exactly what I was looking for.

    Because I have lots of tables with lots of fields means that I have hundreds of different default values and although your method would work, If I understand it correctly I would need a different DynamicDataField for every default value, I'm hoping there's an easier way!

    Thanks anyway, your idea was still useful to me.

    Regards, Andrew

    Tuesday, January 15, 2008 9:53 AM
  • User1641955678 posted

     Hi Andrew,

    Actually, you should be able to change just a few field templates.  Take a look at Text_Edit.ascx.  By default, it sets the current value when you're editing a field, but will get you a blank value when you create a new item.  But you should be able to write code in there to set the value to what you want.

    Of course, you don't want all the fields to get the same value.  What you can do is figure out the value that you want based on the specific field that's being handled.  MetaMember.MemberPropertyInfo will give you that field's PropertyInfo, so potentially you could place a custom attribute in your model that sets the default value, and retrieve it in your Text_Edit.ascx.

    Does that make sense?  We should try to make this a bit easier in the future.

    thanks,
    David

    Tuesday, January 15, 2008 12:19 PM
  • User-69253881 posted

     Hi David!

    I am waiting for the answer on the Andrew's question too. As i understood - it is not perfect the way of writing a lot of custom attributes connected to object(class of table)  when we are going to have a lot of that objects (classes of our tables). Is it possible to write the more power RenderHintAttribute class (now it is sealed) where we can use pairs of attributes with pointed name of field? Like this one: [RenderHint("DateCreation", "DateTime", "1.1.1900")] - where three attributes: name of field, name of ascx template that is now and additionally the third parameter - default value of template in string format (i think by casting string after retrieving of type of field it will work correctly by some logic).

     Sincerely, LukCAD

    Tuesday, January 15, 2008 2:05 PM
  • User1641955678 posted

    Note that there is already an attribute to set a default: [DefaultValue("test")].  So it makes sense to use this instead of trying to make RenderHint do too much.  Note that you may not want a RenderHint if you're happy with the default Text_Edit.ascx, but you just want your defaults to be applied when inserting.

    David

    Tuesday, January 15, 2008 2:18 PM
  • User-69253881 posted

    Yes, you are quite right. In another case we need a lot of constructors of RenderHintAttribute to have possibility to realise different variants:

    [RenderHint("Picture", "DbImage")]

    [RenderHint("Picture", "DbImage", "1X1")]

    [RenderHint("Picture", "DbImage","1X1","INSERT")] 

    Sincerely, LukCAD 

    Tuesday, January 15, 2008 2:46 PM
  • User-69253881 posted

    David, i just not found your second proposal (attribute named as DefaultValue) - may be it in next issue. I did it by your first variant. So i show it for everyone who tries to do the same (makes your own DynamicDataField for insert method when we want to set up different default values by Attribute named as Description):

    look at the code of our new Text_Insert.ascx and Implementation of default value for Category table(for example) for CategoryName filed ,

    at first the control Text_Insert.ascx:

     html:

    <%@ Control Language="C#" CodeFile="Text_Insert.ascx.cs" Inherits="Text_InsertField" %>
    <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ID="reqName" ControlToValidate="TextBox1" Display="Dynamic" Enabled="false" />
    <asp:DynamicValidator runat="server" ID="dynamicValidator" ControlToValidate="TextBox1" Display="Dynamic" />
    <asp:RegularExpressionValidator runat="server" ID="regexValidator" ControlToValidate="TextBox1" Display="Dynamic" Enabled="false" />

      code behind:

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Xml.Linq;
    using System.Web.DynamicData;

    public partial class Text_InsertField : FieldTemplateUserControlBase {
        protected void Page_Load(object sender, EventArgs e) {
            TextBox1.MaxLength = MetaMember.MaxLength;
            if (MetaMember.MaxLength < 20)
                TextBox1.Columns = MetaMember.MaxLength;
                TextBox1.ToolTip = MetaMember.Description;
                TextBox1.Text = MetaMember.Description;

            SetupRequiredFieldValidator(reqName);
            SetupRegexValidator(regexValidator);
            SetupDynamicValidator(dynamicValidator);
            
        }
        
        protected override void ExtractValues(IOrderedDictionary dictionary) {
            if (TextBox1.Text != "")
            {
                dictionary[DataField] = ConvertEditedValue(TextBox1.Text);
            }
        }
    }

     

     


    Now look at the category.cs file with the Category class:

     

    using System;
    using System.Data;
    using System.Configuration;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Web.DynamicData;
    /// <summary>
    /// Summary description for Category
    /// </summary>

    [ImageFormat("Picture", 100, 100)]
    [RenderHint("Picture", "DbImage")]
    [RenderHint("CategoryName", "Text")] // we set up renderhint control
    [Description("CategoryName", "TEST")] // we setup default value by Description attribute
    public partial class Category
    {

    }

      

    Finally we will find that when we press button new in detailsview control we will get prerendered value equals "TEST" for CategoryName field. So now we can reuse our Text_Insert.ascx module much times from many table's objects, we will need only to point pairs of attributes when we will partial classes by only two lines:

     

    [RenderHint("OrderName", "Text")]     // we set up renderhint control
    [Description("OrderName", "New...")] // we setup default value by Description attribute


    Sincerely, LukCAD

    PS: You can repeat this code if you will try expand by yourself this code from this placement(10,2 Mb): download

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 15, 2008 4:43 PM
  • User-1240450359 posted

    LukCAD,

    That's spot on, excellent, thanks for that.

    I can now use the same principle for other types of controls such as Boolean_Insert and Integer_Insert then for most instances you won't even need the [RenderHint] attribute as the right control will be picked for us.

    Regards, Andrew

     

    Wednesday, January 16, 2008 8:27 AM
  • User-1329334484 posted

    Does it work with July Futures release? I need to add mulitile line box to the Details view. Any idea how to do it? The default shows one line only...

    I read that I need to create tablename_details file... Is this correct? 

    Saturday, January 19, 2008 6:44 PM
  • User-1329334484 posted

    I tried this:

    <div>

    <asp:DynamicAutoData id="AutoData1" runat="server" />

    <asp:DynamicDetails ID="DynamicDetails1" runat="server" ControlID="MyDetails" />

    <asp:DetailsView ID="MyDetails" runat="server">

     

    <fields>

    <asp:BoundField DataField="feature_id" HeaderText="feature_id" ReadOnly="True" SortExpression="feature_id" />

    <asp:BoundField DataField="feature_title" HeaderText="feature_title" ReadOnly="false" SortExpression="feature_title" />

    <asp:TemplateField>

    <ItemTemplate>

    <FTB:FreeTextBox id="DescriptionTextBox" Text='<%# Bind("feature_desc") %>' Width="530px" runat="server" SupportFolder="~/ftb/" BreakMode="Paragraph" ></FTB:FreeTextBox>

    </ItemTemplate>

    </asp:TemplateField>

     

    </fields>

    </asp:DetailsView>

    </div>

     

    but getting error:

    StyleSheetTheme is already applied on the control, it cannot be applied more than once.

    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.InvalidOperationException: StyleSheetTheme is already applied on the control, it cannot be applied more than once.

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

    Stack Trace:

    [InvalidOperationException: StyleSheetTheme is already applied on the control, it cannot be applied more than once.]
       System.Web.UI.Control.ApplyStyleSheetSkin(Page page) +2121814
       Microsoft.Web.DynamicDataControls.DynamicExtenderControl`1.OnInit(EventArgs e) +118
       System.Web.UI.Control.InitRecursive(Control namingContainer) +321
       System.Web.UI.Control.InitRecursive(Control namingContainer) +198
       System.Web.UI.Control.InitRecursive(Control namingContainer) +198
       System.Web.UI.Control.InitRecursive(Control namingContainer) +198
       System.Web.UI.Control.InitRecursive(Control namingContainer) +198
       System.Web.UI.Control.InitRecursive(Control namingContainer) +198
       System.Web.UI.Control.InitRecursive(Control namingContainer) +198
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +834
    


    Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

    Saturday, January 19, 2008 6:45 PM
  • User1641955678 posted

    Hi Rafal,

    The July release was entirely different from this one, so pretty much none of what you read in this forum applies to it.  The July release was mostly a prototype to demonstrate the concepts and get some feedback, and it had many limitations and lack of customization.  The current bits remove a lot of those limitations (though we are still improving many aspects).

    If at all possible, you really should try to use the recent bits.

    thanks,
    David

    Saturday, January 19, 2008 7:31 PM
  • User1431397107 posted

    Staggy, not sure if you ever found a solution but I wanted to prepopulate an Insert Date Field with today's date. I managed to override the Databind method in DateTime_EditField control.

    public override void DataBind()

    {
           base.DataBind();
           if (TextBox1.Text == "")     
          {
               TextBox1.Text =
    DateTime.Now.ToShortDateString();
          }
    }

    Thursday, August 28, 2008 5:24 PM