Skip to main content

How to: Add Value Entered by User to LookUpEdit's Data Source

  • 4 minutes to read

This example demonstrates how to allow users to type in the text box and add new values to the lookup’s data source.

  • Drop the WinForms LookUpEdit control onto a form.
  • Set the lookup’s TextEditStyle property to Standard to allow users to type in the text box.
  • Handle the ProcessNewValue event to parse entered values and add new records to the lookup’s data source.

A message box is displayed before a new record is added to the data source. A new value is added to the data source after the user confirms the operation.

LookupEdit_ProcessNewValue_example_EntryAdded

using System;
using System.Windows.Forms;
using System.Collections.Generic;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;

public Form1() {
    InitializeComponent();
    // Binds the lookup to data.
    lookUpEdit1.Properties.DataSource = Task.GetSampleData();
    // Sets the lookup's data fields.
    lookUpEdit1.Properties.DisplayMember = "Caption";
    lookUpEdit1.Properties.ValueMember = "ID";
    // Sets the lookup's value.
    lookUpEdit1.EditValue = 0;
    // Enables adding new values.
    lookUpEdit1.Properties.TextEditStyle = TextEditStyles.Standard;
    lookUpEdit1.ProcessNewValue += new ProcessNewValueEventHandler(this.lookUpEdit1_ProcessNewValue);
}
private void lookUpEdit1_ProcessNewValue(object sender, ProcessNewValueEventArgs e) {
    if((string)e.DisplayValue == String.Empty) return;
    if(XtraMessageBox.Show("Do you want to add a new value?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) {
        List<Task> dataSource = (sender as LookUpEdit).Properties.DataSource as List<Task>;
        dataSource.Add(new Task(dataSource.Count) { Caption = (string)e.DisplayValue });
        e.Handled = true;
    }
}

public class Task {
    int fID;
    public Task(int id) {
        fID = id;
        CreateDate = DateTime.Today;
    }
    public int ID {
        get {
            return fID;
        }
    }
    public string Caption { get; set; }
    public DateTime CreateDate { get; set; }
    public static List<Task> GetSampleData() {
        return new List<Task>() {
            new Task(0){Caption = "Research", CreateDate = new DateTime(2022, 10, 15)},
            new Task(1){Caption = "UI Design", CreateDate = new DateTime(2022, 11, 5)},
            new Task(2){Caption = "Environment Setup", CreateDate = new DateTime(2022, 11, 10)},
            new Task(3){Caption = "Sprint 1", CreateDate = new DateTime(2022, 11, 11)},
            new Task(4){Caption = "Sprint 2", CreateDate = new DateTime(2022, 12, 12)},
            new Task(5){Caption = "Sprint 3", CreateDate = new DateTime(2023, 1, 10)},
            new Task(6){Caption = "Testing", CreateDate = new DateTime(2022, 2, 10)}
        };
    }
}
See Also