简体   繁体   中英

Show a message box when a data row is added to data grid view

As I cannot post to my previous question, I thought of posting it here. This is my code to add a data row from text boxes to a datagridview. I want to show a message box when a data row is added.

My code works but always it does not show the message box for the first record. It shows 5 times the message box for the 6th record, 7 times for the 8th record. And I have a clear button in this form, when I click that also the row added message is getting displayed and shows for the number of times of the records that have in data gridview.

Can anyone find the error in this code..?

Here is my add button code.

//Add button code
private void btnAdd_Click(object sender, EventArgs e)
{
    try 
    {
        //Create a new row in grid view
        DataGridViewRow row = new DataGridViewRow();

        //Create cells
        row.CreateCells(this.myGrid, txtIdNum.Text, txtFname.Text, txtLname.Text, txtEmail.Text);

        //add to data grid view
        this.myGrid.Rows.Add(row);

        //Throw mygrid_RowsAdded when a row is added.
        myGrid.RowsAdded += new DataGridViewRowsAddedEventHandler(myGrid_RowsAdded);
    }
    catch(Exception xx)
    {
        MessageBox.Show(xx.Message);
    }
}

Code for the add row event

// Row add event
void myGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    MessageBox.Show("New record is added..");
    txtIdNum.Text = "";
    txtFname.Text = "";
    txtLname.Text = "";
    txtEmail.Text = "";
}

the first time btnAdd_Click is executed your event handler doesn't get executed because you set it after you add the row ... i suggest you swap your two lines of code like this:

myGrid.RowsAdded += new DataGridViewRowsAddedEventHandler(myGrid_RowsAdded);
this.myGrid.Rows.Add(row);

a better place for setting up the event handler would be in some initialisation code ... the way you do it results in getting more events for each click on the btnAdd button ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM