how to add a new row in datatable

yespalaniappan
02-24-2004, 09:16 AM
Hi:

How do I add the newrow to the existed datatable in
Ado.net? Below is my coding that will give me the error
message An unhandled exception of type 'System.IndexOutOfRangeException' occurred in system.data.dll .Additional information: Cannot find column 0. say, when I
try to click at btnSave_Click to add new row to data
base.(i can also add the namespace ---- imports system.Data.Oledb and try it,it raise the same error)


Dim conn As New OleDb.OleDbConnection("Provider=SQLOLEDB.1;UserID=administrator;Password=palani;Trusted_conne ction=yes;Initial Catalog=palani;Data Source=PALANI")
Dim da As New OleDb.OleDbDataAdapter()
Dim selcust As New OleDb.OleDbCommand("select * from customerdetails", conn)
Dim ds As New DataSet()
Dim dt As DataTable
Dim dr As DataRow
Dim flag As Integer

Private Sub cmdSAVE_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSAVE.Click
If flag = 1 Then
conn.Open()
dt = ds.Tables.Add("CustomerDetails")
dr = dt.NewRow()
dr(0) = CType(txtCustID.Text, Integer)----------------Here ERROR is Raised.
dr(1) = txtName.Text
dr(2) = txtAddress1.Text
dr(3) = txtAddress2.Text
dr(4) = txtCity.Text
dr(5) = CType(txtPhoneNO.Text, Integer)
dr(6) = CType(txtCellNo.Text, Integer)
dr(7) = txtMailID.Text
dt.Rows.Add(dr)
da.Update(ds, "customerdetails")
da.Fill(ds)
conn.Close()
End If
End Sub
:confused:

LuckyShot
02-24-2004, 08:22 PM
Try This:



Dim conn As New OleDbConnection("Provider=SQLOLEDB.1;UserID=administrator;Password=palani;Trusted_conne ction=yes;Initial Catalog=palani;Data Source=PALANI")
Dim da As New OleDbDataAdapter()
da.SelectCommand = new OleDbCommand("select * from customerdetails", conn)
Dim ds As New DataSet()
Dim dt As DataTable
Dim dr As DataRow
Dim flag As Integer

da.Fill(ds)
dt = ds.tables(0)
dr = dt.newrow()
dr(0) = CType(txtCustID.Text, Integer)
dr(1) = txtName.Text
dr(2) = txtAddress1.Text
dr(3) = txtAddress2.Text
dr(4) = txtCity.Text
dr(5) = CType(txtPhoneNO.Text, Integer)
dr(6) = CType(txtCellNo.Text, Integer)
dr(7) = txtMailID.Text
dt.rows.add(dr)
da.update(ds)
conn.close()

but if all you want to do is add a record without using the entire dataset then I would change the line

da.SelectCommand = new OleDbCommand("select * from customerdetails", conn)

to

da.SelectCommand = new OleDbCommand("select * from customerdetails where 1=2", conn)

so to not needlessly waist resources by returning a records that aren't needed

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum