how to simplify codes - vb.net

I have a next button.
theres no error i just want to simplify
Try
lblcat.Text = ds.Tables("evaluation").Rows(cat)("QuestionCategory")
txt1.Text = ds.Tables("evaluation").Rows(CurrentRow)("Question")
txt2.Text = ds.Tables("evaluation").Rows(CurrentRow + 1)("Question")
txt3.Text = ds.Tables("evaluation").Rows(CurrentRow + 2)("Question")
txt4.Text = ds.Tables("evaluation").Rows(CurrentRow + 3)("Question")
txt5.Text = ds.Tables("evaluation").Rows(CurrentRow + 4)("Question")
Catch ex As Exception
End Try
every click to the next button my category and questions change.
every click i want also to save in my database
Private Sub Save_commit()
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
'get connection string declared in the Module1.vb and assing it to conn variable
con = New OleDbConnection(Get_Constring)
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.Text
'I just use the textbox tag property to idetify if the data is new or existing.
sSQL = "INSERT INTO evaluationresult ([Com])" & _
" VALUES (?)"
cmd.CommandText = sSQL
cmd.Parameters.AddWithValue("#FacultyID", txtresult.Text)
'cmd.Parameters.AddWithValue("#IDNumber", OleDbType.Numeric).Value
'cmd.Parameters.AddWithValue("#Com", OleDbType.Numeric).Value
' cmd.Parameters.AddWithValue("#Know", OleDbType.Numeric).Value
'cmd.Parameters.AddWithValue("#Teaching", OleDbType.Numeric).Value
'cmd.Parameters.Addwithvallue("#man", OleDbType.Numeric).Value()
'cmd.Parameters.AddWithValue("#ID", OleDbType.Numeric).Value
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ErrorToString)
Finally
con.Close()
End Try
End Sub
please improve

Related

the connection string property has not been initialized. vb.net access. BELOW is the code

Try
If MsgBox("SAVE THIS ACADEMIC YEAR?", vbYesNo + vbQuestion, title) = vbYes Then
cn.Open()
cm = New OleDbCommand("update [tblay] set status = 'CLOSE'", cn)
cm.ExecuteNonQuery()
cn.Close()
cn.Open()
cm = New OleDbCommand("INSERT INTO [tblay] (aycode,year1,year2,division)values(#aycode,#year1,#year2,#division)", cn)
With cm
.Parameters.AddWithValue("aycode", txtAY.Text)
.Parameters.AddWithValue("year1", txtYear1.Text)
.Parameters.AddWithValue("year2", txtYear2.Text)
.Parameters.AddWithValue("division", cboDivision.Text)
.ExecuteNonQuery()
End With
cn.Close()
MsgBox("NEW ACADEMIC YEAR HAS BEEN SUCCESSFULLY SAVED!", vbInformation, title)
With frmAY
.LoadRecords()
End With
Clear()
End If
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical, title)
End Try
This is the code to load records:
Sub LoadRecords()
Try
DataGridView1.Rows.Clear()
Dim i As Integer
cn.Open()
cm = New OleDbCommand("select * from tblay", cn)
dr = cm.ExecuteReader
While dr.Read
i += 1
DataGridView1.Rows.Add(i, dr.Item("aycode").ToString, dr.Item("year1").ToString, dr.Item("year2").ToString, dr.Item("division").ToString, dr.Item("status").ToString)
End While
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical, title)
End Try
End Sub
This might be more than you want so if so sorry.
SQLite Database (DB) CRUD function are very Boiler Plate Code. That Said I use the same process repetably.
By pacing the code in Using blocks NO need to close the DB and other functions.
I create a button for each function SAVE DELETE and UPDATE that call the function.
Here are the functions.
This code needs to be placed top level
Public connStr As String = "Data Source={0};Version=3;"
Public conn As SQLiteConnection
Here is the SAVE data NOTE the '{gv_dbName} is declared in a Module.
Private Sub InsertSiteData()
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand
cmd.Connection = conn
Try
cmd.CommandText = "INSERT INTO LinkTable (ytChannelName,ytLinkAddress,ytLastVisit,ytSiteType) VALUES (#ytChannelName,#ytLinkAddress,#ytLastVisit,#ytSiteType)"
cmd.Parameters.Add("#ytChannelName", DbType.String).Value = tbSiteName.Text.Trim
cmd.Parameters.Add("#ytLinkAddress", DbType.String).Value = tbUrl.Text.Trim
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.Parameters.Add("#ytSiteType", DbType.String).Value = strType.Trim
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Insert Failed")
End Try
End Using
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub
Here is the DELETE.
Private Sub DeleteSiteData()
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand
cmd.Connection = conn
cmd.CommandText = "DELETE FROM LinkTable WHERE LID =" & gvID
cmd.ExecuteNonQuery()
End Using
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub
And the UPDATE.
Public Sub UpdateSiteData()
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;"),
cmd As New SQLiteCommand("UPDATE LinkTable SET ytChannelName = #ytChannelName, ytLinkAddress = #ytLinkAddress ,ytLastVisit = #ytLastVisit,ytSiteType = #ytSiteType WHERE LID =" & gvID, conn)
conn.Open()
cmd.Parameters.Add("#ytChannelName", DbType.String).Value = tbSiteName.Text.Trim
cmd.Parameters.Add("#ytLinkAddress", DbType.String).Value = tbUrl.Text.Trim
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.Parameters.Add("#ytSiteType", DbType.String).Value = strType.Trim
cmd.Parameters.Add("#LID", DbType.String).Value = gvID
cmd.ExecuteNonQuery()
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub

There is no row at position 0 and System.IndexOutOfRangeException

Error :
An unhandled exception of type 'System.IndexOutOfRangeException'
occurred in System.Data.dll and also showing a :There is no row at
position 0
Dim mycn As New SqlConnection(connection)
Dim DT As New DataTable
mycn.Open()
Dim Adapter As New SqlDataAdapter("SELECT * FROM tblUser where username ='" & txtRet.Text & "'", connection)
Adapter.Fill(DT)
txtUserID.Text = DT.Rows(0)("aid").ToString()
txtFirstName.Text = DT.Rows(0)("fname").ToString()
txtMiddleName.Text = DT.Rows(0)("mi").ToString()
txtLastName.Text = DT.Rows(0)("lname").ToString()
DateOfBirthDateTimePicker.Text = DT.Rows(0)("bday").ToString()
txtAge.Text = DT.Rows(0)("age").ToString()
cmbGender.Text = DT.Rows(0)("gender").ToString()
txtContactNo.Text = DT.Rows(0)("contactno").ToString()
txtEmail.Text = DT.Rows(0)("email").ToString()
txtAddress.Text = DT.Rows(0)("address").ToString()
txtUsernamePS.Text = DT.Rows(0)("username").ToString()
txtPasswordPS.Text = DT.Rows(0)("password").ToString()
rtbSQuestions.Text = DT.Rows(0)("squestion").ToString()
rtbAnswer.Text = DT.Rows(0)("answer").ToString()
Dim bytBLOBData() As Byte = _
DT.Rows(0)("userimage")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
UserPictureBox.Image = Image.FromStream(stmBLOBData)
mycn.Close()
This error indicates that no rows were returned and since you're trying to get the first row (...DT.Rows(0)...) it is throwing the error.
My first suggestion would be to wrap your code in Using statements for all of the objects that implement iDisposable. My second suggestion would be to utilize a parameterized query. My last suggestion would be to check if Rows(0) exists before trying to access it.
Here is a quick example:
'Declare the connection object
Dim con As SqlConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = New SqlConnection(connection)
'Create a new instance of the command object
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM [tblUser] WHERE [username]=#username;", con)
'Parameterize the query
cmd.Parameters.AddWithValue("#username", txtRet.Text)
'Open the connection
con.Open()
'Declare a new adapter to fill the data table
Dim adapter As SqlDataAdapter = New SqlDataAdapter(cmd)
adapter.Fill(DT)
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If DT.Rows.Count > 0 Then
txtUserID.Text = DT.Rows(0)("aid").ToString()
txtFirstName.Text = DT.Rows(0)("fname").ToString()
txtMiddleName.Text = DT.Rows(0)("mi").ToString()
txtLastName.Text = DT.Rows(0)("lname").ToString()
DateOfBirthDateTimePicker.Text = DT.Rows(0)("bday").ToString()
txtAge.Text = DT.Rows(0)("age").ToString()
cmbGender.Text = DT.Rows(0)("gender").ToString()
txtContactNo.Text = DT.Rows(0)("contactno").ToString()
txtEmail.Text = DT.Rows(0)("email").ToString()
txtAddress.Text = DT.Rows(0)("address").ToString()
txtUsernamePS.Text = DT.Rows(0)("username").ToString()
txtPasswordPS.Text = DT.Rows(0)("password").ToString()
rtbSQuestions.Text = DT.Rows(0)("squestion").ToString()
rtbAnswer.Text = DT.Rows(0)("answer").ToString()
End If

Save and Update from Datagridview to Access Database

i've been fumbling with this problem for a while now. am trying to update/insert into my access database data from a datagridview on a form.
i've a maskedtextbox that i've masked to suit my primary key. when the mask is completed then automatically, records are read from the database to the textboxes and datagridview as shown in the attached picture.
i did that with this code
If STHN_ID.MaskCompleted = True Then
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
'da = New OleDbDataAdapter("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn) 'Change items to your database name
'da.Fill(ds)
'Dim view As New DataView(tables(0))
'source1.DataSource = view
'DependantView.DataSource = view
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
'connection.Open()
Dim myTable As DataTable = New DataTable
adapter.Fill(myTable)
DependantView.DataSource = myTable
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
my headache now is to update/insert into the database when records are added/edited in the datagridview based on the STHN_ID entered in the maskedtextbox. any help would be really appreciated.
sample
this is how i got it done!
on maskedtextbox with mask completed this is the code to read from database and load datagridview ...........
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
con = New OleDbConnection
con.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\PRINCE\Documents\STHNDatabase.accdb")
con.Open()
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
Dim connection As New OleDbConnection
connection.ConnectionString = connString
adapt = New OleDbDataAdapter("Select [DependentID],[DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship],[STHN_ID] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", con)
ds = New DataSet
adapt.Fill(ds, "DependantData")
DependantView.DataSource = ds.Tables(0)
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
and on the SaveButton Click this is the code.....
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
Try
builder = New OleDbCommandBuilder(adapt)
adapt.Update(ds, "DependantData")
MsgBox("Updated Successfully")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
thanks once again. really appreciate it

Populating Datagrid

I am creating a pageant scoring system,
I have this functions for populating my datagridview's first column using query:
Public Sub searchContestant()
If comboCategory.SelectedIndex <> 0 Then
Dim id As Integer = Login.JudgeBindingSource1.Current("Cont_id")
Dim critID As Integer = Convert.ToInt32(lblID.Text)
'search the contest record by the contest_id
Dim con As New SqlConnection
Dim reader As SqlDataReader
Dim reader2 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
Try
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & critID & "' ", con)
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
' Execute Query
reader = cmd.ExecuteReader()
nc.Name = "Contestants"
nc.Width = 250
nc.ReadOnly = True
DataGridView1.Columns.Add(nc)
While reader.Read()
nc = New DataGridViewTextBoxColumn
nc.Name = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.HeaderText = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.Width = 150
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
Try
'populate contestant rows
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
reader2 = cmd2.ExecuteReader()
While reader2.Read()
nc = New DataGridViewTextBoxColumn
nc.Width = 100
DataGridView1.Rows.Add(reader2.GetString(2).ToString())
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End If
End Sub
And for succeeding columns :
Public Sub searchCriteria()
Dim con As New SqlConnection
Dim reader4 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
Try
'populate Criteria
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & lblID.Text & "' ", con)
con.Open()
reader4 = cmd.ExecuteReader
While reader4.Read
nc = New DataGridViewTextBoxColumn
nc.Name = reader4.GetString(1).ToString & Chr(13) & reader4.GetString(2).ToString & "%"
nc.Width = 100
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End Sub
This is the output:
And everytime a judge login, I insert data into the system with this function:
Public Sub makeTransaction()
Dim con2 As New SqlConnection
'get the judge id upon logging in
Dim judgeID = Login.JudgeBindingSource1.Current("Judge_id")
'get the contest id of the judge
Me.JudgeTableAdapter.FillByJudgeID(Me.PSSDataSet.Judge, judgeID)
Dim JudgeContestid = Login.JudgeBindingSource1.Current("Cont_id")
Me.ContestantTableAdapter.FillByContestID(Me.PSSDataSet.Contestant, JudgeContestid)
'get the contestant id
Me.ContestTableAdapter.FillByContestID(Me.PSSDataSet.Contest, JudgeContestid)
Dim contestID As Integer = ContestBindingSource.Current("Cont_id")
'get the category of the contest
Me.CategoryTableAdapter.FillByContestID(Me.PSSDataSet.Category, Convert.ToInt32(contestID))
For Each Category As DataRow In Me.PSSDataSet.Category.Rows
Me.CriteriaTableAdapter.FillByCategoryID(Me.PSSDataSet.Criteria, Category("Cat_id"))
For Each Contestant As DataRow In Me.PSSDataSet.Contestant.Rows
For Each Criteria As DataRow In Me.PSSDataSet.Criteria.Rows
TransactionsTableAdapter.Insert(JudgeContestid, Contestant("Con_id"), Criteria("Cri_id"), 0)
Next
Next
Next
End Sub
Now my problem is, how can I populate the datagrid using the data recently made by MakeTransaction() function?

error :ExecuteNonQuery: CommandText property has not been initialized

this code is in the button click , i get each data out using spilt
but i encounter error at "cmd.CommandType = CommandType.Text"
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
the same code , the below work
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO GuestList (groupID,guest,contact,eEmail,relationship,info,customerID) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}'); ", sqlStatement, splitItems(0), splitItems(1), splitItems(2), splitItems(3), splitItems(4), splitItems(5), Session("customerID"))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
You never set the CommandText property.
You don't need to set CommandType at all.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
dim dt as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblGender )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox1
.DataSource = dt
.DisplayMember = "Gender"
End With
dim dt1 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblStatus )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox2
.DataSource = dt1
.DisplayMember = "Status"
End With
dim dt2 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblDepartment )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox3
.DataSource = dt2
.DisplayMember = "Department"
End With
End Sub
See this
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
'Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
'If item.Contains(",") Then
' splitItems = item.Split(",".ToCharArray())
' sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
'End If
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}({1},'{2}'); ", sqlStatement, splitItems(0), splitItems(1))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try