Home > Software engineering >  how to stop duplicate value from text box to enter in datagridview which is connected to access db i
how to stop duplicate value from text box to enter in datagridview which is connected to access db i

Time:12-21

i am passing value from text box to datagridview which is also inserted in access db. but its also accepting duplicate values in datagridview. how do i prevent duplicates values ? here is picture project is in C# .Net framework.



here is Add button click event

private void AddButton_Click(object sender, EventArgs e) {

                    try
        {
            connection = new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=F:\\Floro_sense\\Floros.mdb");
            connection.Open();


            OleDbCommand command = new OleDbCommand("INSERT INTO Sflorotype(Sflorovalues, Sflorotypes) VALUES ('"   ValueTextBox.Text   "','"   TypeTextBox.Text   "');", connection);
            var result = command.ExecuteNonQuery();

            OleDbDataAdapter adapter = new OleDbDataAdapter("select * from Sflorotype", connection);
            DataTable table = new DataTable();
            adapter.Fill(table);

            var data = string.Join(Environment.NewLine,
            table.Rows.OfType<DataRow>().Select(x => string.Join(" ; ", x.ItemArray)));

            BindingSource bind = new BindingSource();
            bind.DataSource = table;
            dataGridViewList.DataSource = bind;
            adapter.Update(table);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            connection.Close();

        }

    }

CodePudding user response:

You can write a method to check that a florotype already exists and use this method before inserting to the DB. If the FloroTypeExists() returns true then show a message box saying that the floro type already exists and do not add it to the DB.

(Pseudo-code)

private bool FloroTypeExists(string floroType)
{
  // Get your connection here
  string strSql = "select * from Sflorotype where Sflorotypes = '"   floroType   "'";
  OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, connection);
  DataTable table = new DataTable();
  adapter.Fill(table);
  bool floroTypeExists = (table.Rows.Count > 0);
  return floroTypeExists;      
}

Some notes: You should refactor your code to write DB access code in dedicated classes and not in your Button click handler. Also you should not hard-code your DB conection strings and put them in config files.

CodePudding user response:

You have to check the data before inserting the values into your database if you are not using marking the fields in db, whether you want it to be Unique key or a Composite key. If the select statement gives you any record, than you don't have to add it to db.

  • Related