Hello everyone,

Is there a way to limit the number of records to be inserted into a table using ado.net. For example i need to insert only 5 records into table, the table should not allow me to insert the 6th record. I am new .net can anyone pls help...

Thank You

Get the row count of the table, if it is less than 5 (or 6 I'm unsure what you want) then insert the new entry, otherwise, show some error message and return from the method.

To do this at the database level you would need to create a trigger which runs on a database insert. Which does the same as the above.

If so, you can do something like this:

private void PopulatingDataTable()
        {
            int max = 5;
            DataTable table = new DataTable("myTable");
            table.Columns.Add(new DataColumn("1stColumn", typeof(int)));
            table.Columns.Add(new DataColumn("2ndColumn", typeof(string)));

            DataRow dr;
            //examples to insert to dt:
            string[] names = new string[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg" };
            for (int i = 0; i < names.Length; i++)
            {
                if (i < max)
                {
                    dr = table.NewRow();
                    dr["1stColumn"] = i + 1;
                    dr["2ndColumn"] = names[i];
                    table.Rows.Add(dr);
                }
                else
                {
                    MessageBox.Show("There is more then 5 items available to insert into table.");
                    break;
                }
            }
        }
This article has been dead for over six months. Start a new discussion instead.