Skip to main content
All docs
V24.2

Smart Paste AI-powered Extension

  • 9 minutes to read

“SmartPaste” is an AI-powered feature that transforms the traditional copy-and-paste process into a smarter, more efficient tool. Designed to improve productivity, SmartPaste analyzes the content you copy and intelligently assigns the right values to the appropriate fields or row cells in the DevExpress Data Grid and LayoutControl-driven forms.

Run Demo

Applies To

How It Works

DevExpress UI controls seamlessly integrate SmartPaste. When SmartPaste is activated, the “Smart Paste” command is automatically added to a control’s popup menu.

When you copy data from a source (such as a spreadsheet, document, or web page) and paste it into a data grid or LayoutControl-driven form, SmartPaste automatically interprets the content and maps the data to the correct data fields or cells. Play the following animation to see a demonstration:

AI-powered Smart Paste Extension for WinForms | DevExpress

Tip

You can also specify a shortcut key to invoke SmartPaste.

See the following section in this help topic for an example: Invoke SmartPaste Using a Shortcut.

Activate SmartPaste

1. Install DevExpress NuGet Packages

  1. DevExpress.AIIntegration.WinForms
  2. Install one of the following DevExpress NuGet packages depending on which AI client you use:
    • DevExpress.AIIntegration.OpenAI
    • DevExpress.AIIntegration.Azure.OpenAI
    • DevExpress.AIIntegration.Ollama
  3. DevExpress.Win.Design (enables design-time features for DevExpress UI controls)

Read the following help topics for information on how to obtain the DevExpress NuGet Feed and install DevExpress NuGet packages:

2. Register AI Client

The following code snippet registers the Azure OpenAI client:

using Microsoft.Extensions.AI;
using DevExpress.AIIntegration;

internal static class Program {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        IChatClient asChatClient = new Azure.AI.OpenAI.AzureOpenAIClient(new Uri(AzureOpenAIEndpoint),
            new System.ClientModel.ApiKeyCredential(AzureOpenAIKey))
            .AsChatClient("GPT4o");
        AIExtensionsContainerDesktop.Default.RegisterChatClient(asChatClient);
        Application.Run(new Form1());
    }
    static string AzureOpenAIEndpoint { get { return Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT"); } }
    static string AzureOpenAIKey { get { return Environment.GetEnvironmentVariable("AZURE_OPENAI_APIKEY"); } }
}

Tip

Read the following help topic for additional information: How to Register an AI Client.

3. Create and Configure SmartPaste Behavior

  1. Drop the BehaviorManager component from the Toolbox onto a Form.
  2. Add a SmartPasteBehavior, configure its settings, and attach the behavior to a DevExpress UI control (GridControl, LayoutControl, or DataLayoutControl). You can do this at design time or in code:

    Create a SmartPasteBehavior at Design Time - WinForms UI Controls, DevExpress

    public Form1() {
        InitializeComponent();
        behaviorManager1.Attach<SmartPasteBehavior>(advBandedGridView1, behavior => {
            behavior.Properties.ItemDescriptions.AddRange(new List<AIItemDescription>() {
                    new AIItemDescription(advBandedGridView1.Columns["ProductName"], "Official name or product name."),
                    new AIItemDescription(advBandedGridView1.Columns["ShippingWeight"], "Weight of the product when packaged for shipping (in lbs or kg)."),
                    new AIItemDescription(advBandedGridView1.Columns["ProductDimensions"], "Physical size of TV without stand, typically in length, width, and height (in inches or mm)."),
                    new AIItemDescription(advBandedGridView1.Columns["ShippingDimensions"], "Physical size of shipping package, typically in length, width, and height (in inches or mm)."),
                    new AIItemDescription(advBandedGridView1.Columns["Warranty"], "Information related to the product warranty (in years or months)."),
                }
            );
            behavior.Properties.ExcludedItems.Add(advBandedGridView1.Columns["Notes"]);
        });
    }
    

The animation below shows how SmartPaste works in the DevExpress Grid Control:

SmartPaste - WinForms Data Grid, DevExpress

SmartPasteBehavior APIs

Once you attach the SmartPasteBehavior to a control, you should describe items so that SmartPaste can assign the right values to appropriate items. In the context of SmartPaste, an item refers to a LayoutControlItem when working with a LayoutControl, or a GridColumn when working with a GridControl.

Item Descriptions

Note

Item descriptions are optional if an item’s text or caption is specified (for example, a grid column’s Caption property or layout item’s Text property is set to a non-empty string). Although SmartPaste attempts to determine the right value for an item based on the item’s text/caption, we recommend that you also describe items for improved accuracy.

Use the SmartPasteBehavior.Properties.ItemDescriptions collection property to add descriptions (AIItemDescription) for certain items. Each AIItemDescription object in the collection has two properties:

  1. AIItemDescription.Item: A component that will receive the pasted data (GridColumn or LayoutControlItem).
  2. AIItemDescription.Description: A string that describes the expected content and/or data format for the item.

Excluded Items

If you want to exclude a specific item from SmartPaste, you can add this item to the ExcludedItems collection. This allows you to exclude grid columns or data fields from being affected by SmartPaste, ensuring that they remain unchanged.

SmartPaste API

Invoke SmartPaste Using a Shortcut

The following code snippet handles the GridView’s KeyDown event to invoke SmartPaste when a user presses Alt+P:

async void AdvBandedGridView1_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyCode == Keys.P && e.Modifiers == Keys.Alt)
        await behaviorManager1.GetBehavior<SmartPasteBehavior>(gridView1).SmartPasteAsync();
}

SmartPaste Result Formatting

When pasting into data fields of basic data types (such as Boolean, date-time, numeric, string), SmartPaste automatically appends default formatting prompts to item descriptions. You can also specify custom formatting prompts as needed.

For example, if your data source designates Boolean values as 1 and -1, you can specify the following item description: “If 1 use True. If -1 use False.”

behaviorManager1.Attach<SmartPasteBehavior>(layoutControl1, behavior => {
    behavior.Properties.ItemDescriptions.AddRange(new List<AIItemDescription>() {
            new AIItemDescription(itemInStock, "If 1 use True. If -1 use False.")
        }
    );
});

SmartPaste Result Validation

You can validate a SmartPaste result to ensure that the data adheres to predefined rules or formats required by your application. Use built-in APIs of DevExpress controls to analyze, and if necessary, modify the data returned by SmartPaste.

For data editors, handle the EditValueChanging event to analyze and modify SmartPaste results. This event is triggered whenever the EditValue property of a control is about to change and allows you to modify the value before it is finalized.

The following example handles the Lookup’s EditValueChanging event to specify the EditValue based on the value (display text) returned by SmartPaste:

public Formatting() {
    InitializeComponent();
    InitLookup();
    SmartPasteLayoutBehaviorSource.Register();
    behaviorManager1.Attach<SmartPasteBehavior>(layoutControl1, behavior => {
        behavior.Properties.ItemDescriptions.AddRange(new List<AIItemDescription>() {
                new AIItemDescription(itemSeller, "The name of the individual or company selling the product.")
            }
        );
    });
}

void LookUpEdit1_EditValueChanging(object sender, ChangingEventArgs e) {
    List<DataItemSeller> list = (sender as LookUpEdit).Properties.DataSource as List<DataItemSeller>;
    var item = list.Find(item => item.Seller == e.NewValue.ToString());
    if (item != null)
        e.NewValue = item.ID;
    else
        e.Cancel = true;
}

void InitLookup() {
    lookUpEdit1.Properties.DataSource = new List<DataItemSeller>() {
        new DataItemSeller(){ Seller = "Seller A", Rating = 4.6 },
        new DataItemSeller(){ Seller = "Seller B", Rating = 4.7 },
        new DataItemSeller(){ Seller = "Seller C", Rating = 4.8 },
    };
    lookUpEdit1.Properties.DisplayMember = "Seller";
    lookUpEdit1.Properties.ValueMember = "ID";
    lookUpEdit1.EditValueChanging += LookUpEdit1_EditValueChanging;
}

public class DataItemSeller {
    Guid id;
    public DataItemSeller(){
        id = Guid.NewGuid();
    }
    public Guid ID { get { return id; } }
    public string Seller { get; set; }
    public double Rating { get; set; }
}

Read the following help topic for additional information and examples on how to validate changes in the Data Grid control: Validate User Input in Data Grid.

Data Grid and Layout Control Specifics

SmartPaste in Data Grid

  • All View types support SmartPaste.
  • In GridView, BandedGridView, and AdvBandedGridView, a user can right-click a data row or new item row and invoke a popup menu with the “Smart Paste” command.
  • For other View types, you should implement a shortcut or popup menu to execute SmartPaste.

Grid column requirements include:

  • The column must be visible. The column’s Visible property must be set to true.
  • The column must not be read-only.
  • The column’s Caption property should be set to a non-empty string if the column’s description is not specified in SmartPaste behavior properties.

Values are pasted into grid cells as strings. The grid automatically converts string values to appropriate data types, which include:

  • Numeric Types: int, uint, short, ushort, float, double, decimal, etc.
  • Date-Time Types: DateTime, DateOnly, TimeOnly.
  • Boolean

SmartPaste in Layout Control

Layout items support SmartPaste if they meet the following requirements:

  • The layout item must contain a BaseEdit descendant control (for example, TextEdit, DateEdit, SpinEdit).
  • The layout item must be visible. The layout item’s Visible property must be set to true.
  • The layout item must be enabled. The layout item’s Enabled property must be set to true.
  • The layout item’s Text property should be set to a non-empty string if the layout item’s description is not specified in SmartPaste behavior properties.

The following data editors automatically convert SmartPaste results before they are assigned to the EditValue property:

For editors that do not support built-in conversion, handle the EditValueChanging event to manually convert string values as needed.

See Also