aminvincent
aminvincent

Reputation: 603

Prevent duplicate value in gridcontrol devexpress using data table

Fill txtName, txtAddress and press btnSubmit will give and add value to GridControl DevExpress.

This the codes:

DataTable dt;

private void XtraForm1_Load(object sender, EventArgs e)
{
    dt = new DataTable();
    DataColumn dc1 = new DataColumn("NAME");
    DataColumn dc2 = new DataColumn("ADDRESS");
    dt.Columns.Add(dc1);
    dt.Columns.Add(dc2);
    DataRow dr1 = dt.NewRow();
    gridControl1.DataSource = dt;
}

private void btnSubmit_Click(object sender, EventArgs e)
{
    DataRow dr1 = dt.NewRow();
    dr1[0] = txtName.Text;
    dr1[1] = txtAddress.Text;
    dt.Rows.Add(dr1);
    gridControl1.DataSource = dt;
}

The codes above worked properly.

How can I prevent duplicate value when data exist in GridControl? I want to get alert / message box that showing me duplicate value after btnSubmit pressed.

Upvotes: 0

Views: 1454

Answers (1)

nempoBu4
nempoBu4

Reputation: 6631

You can use DataTable.Select method to find the existed rows in your DataTable. If there are no rows, then you can add new row, else you can show the message.
Here is example:

private void btnSubmit_Click(object sender, EventArgs e)
{
    string name = txtName.Text;
    string address = txtAddress.Text;

    var rows = dt.Select(string.Format("NAME = '{0}' AND ADDRESS = '{1}'", name, address));

    if (rows.Length == 0)
    {
        DataRow dr1 = dt.NewRow();
        dr1[0] = name;
        dr1[1] = address;
        dt.Rows.Add(dr1);
    }    
    else
        MessageBox.Show("Some message.");        
}

Upvotes: 1

Related Questions