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

6th record should allow nulls then just insert a null value there.

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.

Is there a way to limit the number of records to be inserted into a table using ado.net?

What kind of table are you talking about? DataTable?

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;
                }
            }
        }

Thank you all helped me a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.