Avoid (Prevent) duplicate record insert into DataTable using C# in ASP.Net

Last Reply one month ago By dharmendr

Posted one month ago

I want to prevent user to input duplicate number in gridview, as i tried but not working here is my c# Code.

i am inserting data into gridview using viewstate from textboxes

                        if (DropDownList1.SelectedItem != null)
                        {
                            // get value and text which item you have selected
                            int codeitem = Convert.ToInt32(DropDownList1.SelectedItem.Value.ToString());
                            string Descriptionitem = DropDownList1.SelectedItem.Text.ToString();

                         
                            //add the selected item to gridview

                            DataTable dtgridview = ViewState["dt"] as DataTable;
                            DataRow dr2 = dtgridview.NewRow();
                            bool ifExist = false;
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (dr2["Prdno"].ToString() == TextBox1.Text.Trim())
                                {
                                    ifExist = true;
                                }

                            }
                            if (!ifExist)
                            {
                                dr2["Prdno"] = TextBox1.Text.Trim();
                                dr2["Codeitem"] = codeitem;
                                dr2["Descriptionitem"] = Descriptionitem;
                                dr2["Orderno"] = txtorderno.Text;

                                dr2["QTY"] = txtqty.Text;
                                dtgridview.Rows.Add(dr2);
                                ViewState["dt"] = dtgridview;
                                GridView1.DataSource = dtgridview;
                                GridView1.DataBind();
                            }
                            else
                            {
                                this.lbmsg.Visible = true;
                            }
                           
                            clear();
                        }

 

Posted one month ago
akhter says:
foreach (DataRow dr in dt.Rows)
                            {
                                if (dr2["Prdno"].ToString() == TextBox1.Text.Trim())
                                {
                                    ifExist = true;
                                }

                            }

Change above with below code.

foreach (DataRow dr in dtgridview.Rows)
{
    if (dr["Prdno"].ToString() == TextBox1.Text.Trim())
    {
        ifExist = true;
        break;
    }

}