2

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();
        }
    }
5
  • 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. Commented Apr 7, 2017 at 4:39
  • 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()); } Commented Apr 7, 2017 at 5:21
  • The code you shared in the comment worked? Are you facing any other issue? Commented Apr 7, 2017 at 5:54
  • 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" Commented Apr 7, 2017 at 6:00
  • 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. Commented Apr 7, 2017 at 6:16

1 Answer 1

-1

Use below to refresh the current cell's value,

dataGridView.RefreshEdit();
dataGridView.Refresh();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.