2
votes

I'm trying to display an error message, if the rows in the datagridview match the new value I entered in . The problem is that after I add a new datagridview with:

            Product c = new Product();
            tableProducts.Products.Add(c);
            productBindingSource.Add(c);
            productBindingSource.MoveLast();

A new row is created, and when I want to save it, it compares this row code with that of the textbox and causes the error message to be displayed. But it should only be compared with those already stored in the table, not the one I add as new:

Here is the code:

private void btnSave_Click(object sender, EventArgs e)

    {
        if (dataGridView.CurrentRow.Cells[0].Value.ToString() == txtCode.Text && txtCode.Enabled == true)
        {
            MessageBox.Show("Code already exist! Try another one!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            panel.Enabled = false;
            defaultViewButtons();
        }
        else
        {
                productoBindingSource.EndEdit();
                tablaProductos.SaveChangesAsync();
                panel.Enabled = false;
                defaultViewButtons();
        }
    }
1
You need to loop thru all the rows of gridview except the last one (which is added just now) and compare value of Cell[0] of each row to the textCode.Text and if you find the match any where you break out of the loop and display the message. If loop ends without break you proceed with the save.Chetan
I think I'm close to solving it. Thank you very much for your answer! private void btnSave_Click(object sender, EventArgs e) { for (int i = 0; i < dataGridView.Rows.Count -1; i++) { MessageBox.Show(dataGridView.Rows[i].Cells[0].Value.ToString()); }John Malkovich
The code you shared in the comment worked? Are you facing any other issue?Chetan
This is the complete code: pastebin.com/Y8jd5FfK It works fine, if the code is not repeated. But now the new error I have when trying to save is: "A second operation started on this context before a previous asynchronous operation completed"John Malkovich
This the code from before, but fixed... lol pastebin.com/L0CkFH96 Thanks a lot, I was having a hard time with this, and the truth was that it was not so complicated ... but I could not solve it by myself. Your first comment guided me along the necessary path.John Malkovich

1 Answers

-1
votes

Use below to refresh the current cell's value,

dataGridView.RefreshEdit();
dataGridView.Refresh();