简体   繁体   中英

Error on Delete Last row of DataGridview on Winform Application in c#

I am working in Window application in asp.net. I have a GUI in which user enter a product name and quantity in text boxes. On Add button click i am adding a new row in Datagridview and set the value of productname and quantity in datagridview columns. I am not inserting record in Database and I am only save record in Datatable as well add record in Datagridview.

Problem is that when I select a last row from datagridview and press delete button from keyboard then it generate an error Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

static public DataTable gdt;
    private void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtItemCode.Text.Trim() == "")
            {
                MessageBox.Show("Enter Item Code");
                txtItemCode.Focus();
                return;
            }
            if (txtQty.Text.Trim() == "")
            {
                MessageBox.Show("Enter Qty");
                txtQty.Focus();
                return;
            }
            if (Convert.ToInt32(txtQty.Text.Trim()) <= 0)
            {
                MessageBox.Show("Qty must be greater than 0");
                txtQty.Focus();
                return;
            }

            if (btnAdd.Text == "ADD")
            {

                DataRow[] dr = gdt.Select("Item_Code = '" + txtItemCode.Text.Trim() + "'");

                if (dr.Length > 0)
                {
                    MessageBox.Show("Item Code Already Exist.");
                    txtItemCode.Text = "";
                    txtItemCode.Focus();
                    return;
                }

                tblItemMasterBLL oItem = new tblItemMasterBLL();
                int ItemID = 0;
                DataTable dt = new DataTable();
                dt = oItem.getItemDetailByItemCode(txtItemCode.Text.Trim());
                if (dt.Rows.Count > 0)
                {
                    ItemID = Convert.ToInt32(dt.Rows[0]["Item_ID"]);


                    gdt.Rows.Add();

                    gdt.Rows[gdt.Rows.Count - 1]["Item_Code"] = txtItemCode.Text.Trim();
                    gdt.Rows[gdt.Rows.Count - 1]["Item_ID"] = ItemID;
                    gdt.Rows[gdt.Rows.Count - 1]["Qty"] = txtQty.Text.Trim();

                    gdt.Rows[gdt.Rows.Count - 1]["Article_Desc"] = Convert.ToString(dt.Rows[0]["Article_Desc"]);
                    gdt.Rows[gdt.Rows.Count - 1]["Color_Desc"] = Convert.ToString(dt.Rows[0]["Color_Desc"]);
                    gdt.Rows[gdt.Rows.Count - 1]["Size_Desc"] = Convert.ToString(dt.Rows[0]["Size_Desc"]);
                    gdt.Rows[gdt.Rows.Count - 1]["MRP"] = Convert.ToString(dt.Rows[0]["MRP"]);


                    dgv_Items.DataSource = null;
                    dgv_Items.DataSource = gdt;




                }
                else
                {
                    MessageBox.Show("Invalid Item Code");
                }
                txtItemCode.Text = "";
                txtQty.Text = "";
            }
            else if (btnAdd.Text == "UPDATE")
            {
                if (gdt.Rows.Count > 0)
                {
                    gdt.Rows[Convert.ToInt32(lblhdnRowIndex.Text)]["Qty"] = txtQty.Text.Trim();
                    dgv_Items.Rows[Convert.ToInt32(lblhdnRowIndex.Text)].Cells["Qty"].Value = txtQty.Text.Trim();
                }
                txtItemCode.ReadOnly = false;
                txtItemCode.Text = "";
                txtQty.Text = "";
                lblhdnItemID.Text = "";
                lblhdnItemCode.Text = "";
                lblhdnQty.Text = "";
                btnAdd.Text = "ADD";
                lblhdnRowIndex.Text = "";
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void dgv_Items_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
    {
        try
        {
            if (MessageBox.Show("Do you want to delete the current row?", "Confirm deletion",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                ScrollPosition = 0;
                ScrollPosition = dgv_Items.FirstDisplayedScrollingRowIndex;
                int iIndex = dgv_Items.CurrentRow.Index;

                    gdt.Rows.RemoveAt(iIndex);

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void dgv_Items_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
    {
        try
        {
            dgv_Items.DataSource = null;
            dgv_Items.DataSource = gdt;
            dgv_Items.Rows[dgv_Items.Rows.Count - 1].Visible = false;

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

How about ..

ScrollPosition = 0;
dgv_Items.FirstDisplayedScrollingRowIndex=ScrollPosition;
int iIndex = dgv_Items.CurrentRow.Index;

gdt.Rows.RemoveAt(iIndex);

thanks all of u participate to solve my problem. Actually this is index problem. I have find out the solution In which I have done changes in UserDeletingRow event of Datagridview. I have added a new line in UserDeletingRow eventhich is in bold font. Now my code is working fine.

private void dgv_Items_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
            {
                try
                {
                    if (MessageBox.Show("Do you want to delete the current row?", "Confirm deletion",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        ScrollPosition = 0;
                        ScrollPosition = dgv_Items.FirstDisplayedScrollingRowIndex;
                        int iIndex = dgv_Items.CurrentRow.Index;

                            DataRow dr = gdt.Rows[iIndex]; //new added code
                            gdt.Rows.RemoveAt(iIndex);
                            gdt.Rows.InsertAt(dr, iIndex); //new added code
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

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