Add New Row in DataGridView Programmatically

Submitted by: 
Visitors have accessed this post 10082 times.

In some cases, you want to add new rows to the DataGridView programmatically. If you are using a data-bound DataGridView control, you cannot easily use the cells properties of the DataGridView control.

All you need to do is use the dataset where the DataGridView control is connected. Say you want to get the record from employees table and put it in DataGridView.

Here’s how to do it:

  1. Dim strSQL As String
  3. strSQL = "SELECT * FROM Employees"
  5. Dim cmd As OleDbCommand = New OleDbCommand(strSQL, conn)
  6. 'create data reader
  7. Dim rdr As OleDbDataReader = cmd.ExecuteReader
  9. While rdr.Read
  10. Dim newRow As PayrollDataSet.PayrollRow = PayrollDataSet.Payroll.NewPayrollRow
  12. newRow.EmployeeID = rdr("EmployeeID")
  13. newRow.MonthlySalary = rdr("MonthlySalary")
  14. newRow.SSSCont = rdr("SSSCont")
  15. newRow.SalaryLoan = rdr("SalaryLoan")
  16. newRow.NetIncome = rdr("MonthlySalary") - rdr("SSSCont") - rdr("SalaryLoan")
  18. PayrollDataSet.Payroll.Rows.Add(newRow)
  19. End While

Download the VB.NET Project on Adding Rows to Data-Bound DataGridView.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.