开发者

Prevent duplicate records when I save the values into the ComboBox - C#

I have been saving into the ComboBox a value out of the selected column in datagridview with below code. My question is:How can I prevent duplicate records when I save the开发者_如何转开发 values into the ComboBox? How can I do that?

Code:

int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;          
CmbAra.Text = "";

for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
    CmbAra.Items.Add(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString());
}


Please try this

    private void dgvServerList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            if (e.ColumnIndex == 1)
            {
                string id = dgvServerList[e.ColumnIndex, e.RowIndex].Value.ToString();
                int duplicaterow = 0;

                for (int row = 0; row < dgvServerList.Rows.Count; row++)
                {
                    if (row != e.RowIndex && id == dgvServerList[e.ColumnIndex, row].Value.ToString())
                    {
                        duplicaterow = row + 1;
                        MessageBox.Show("Duplicate found in the row: " + duplicaterow);
                        this.dgvServerList[e.ColumnIndex, e.RowIndex].Value = "";
                        break;
                    }
                }
            }
        }
        catch
        {
        }
    }


you could first transfer your datagridview items to a dictionary (which guarantees uniqueness) and then transfer that dictionary content to the combobox. or you could check for uniqueness yourself using a 'Contains' method on the combobox. you could even tie the dictionary to the combobox as a source for the combobox items.

Dictionary<string,bool> d = new Dictionary<string,bool>();
int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;
CmbAra.Text = "";
for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
   d[dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString()] = true;
}
CmbAra.Items.AddRange(d.Keys);


Use a set:

    int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;

    CmbAra.Text = "";

    HashSet<string> set = new HashSet<string>();

    for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
    {
        string s = dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString();
        if(!set.Contains(s)) {
            CmbAra.Items.Add(s);
            set.Add(s);
        }           
    }


by using the following check and then determine to add or not

if(CmbAra.Items.Contains(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString()))


You can use the following code part.

if(!(CmbAra.Items.Contains(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString())))
{
   CmbAra.Items.Add(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString());
}
else
{
   MessageBox.Show("Value Already exists , not added");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜