parameter causes the data unreadable in the form 2 does not appear on the web version of vb.net - vb.net

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim id As String, sLogon_User As String, sAuth_User As String, sUser_ID As String
Dim sServer_Name As String
Dim sIP_Address As String
sIP_Address = Request.ServerVariables("REMOTE_ADDR")
Dim hit As New PagePosting
Dim currentPosting As Posting = CmsHttpContext.Current.Posting
Dim webContext As WebAuthorContext
webContext = WebAuthorContext.Current
'sNama_Perusahaan = Request.QueryString("sentraID")
'Response.Write("masuk sini dgn nilai = " & CmsHttpContext.Current.CmsQueryString())
sData = ""
If Not Page.IsPostBack Then
'sNama_Perusahaan = Request.ServerVariables("sentraID")
sNama_Perusahaan = Request.QueryString("sentraID")
' sNama_Perusahaan = Request.QueryString("sentraID")
Response.Write("masuk sini dgn nilai = " & Request.QueryString("sentraID") & sNama_Perusahaan)
tampil(sNama_Perusahaan)
End If
Sub tampil(ByVal sParam As String)
Dim rd As SqlDataReader
Dim myConnection = New SqlConnection(ConfigurationSettings.AppSettings("RegBIK"))
myConnection.Open()
Dim adadata As Integer
' Dim myCommand As New SqlCommand("select count (*) from kuesioner where ltrim(rtrim(NmPerush)) ='aaa'", myConnection)
Dim myCommand As New SqlCommand("select count (*) from kuesioner where ltrim(rtrim(NmPerush)) ='&sParam'", myConnection)
rd = myCommand.ExecuteReader
While rd.Read
adadata = rd.GetInt32(0)
End While
myConnection.close()
Try
If adadata > 0 Then
myConnection.Open()
' Dim myCommands As New SqlCommand("select * from kuesioner where ltrim(rtrim(NmPerush)) ='aaa'", myConnection)
Dim myCommands As New SqlCommand("select * from kuesioner where ltrim(rtrim(NmPerush)) ='&sParam'", myConnection)
rd = myCommands.ExecuteReader
While rd.Read
disabledAll()
Me.btnUpload.Enabled = False
Me.btnPreview.Enabled = True
txtNmPerush.Value = rd.GetString(1)
Me.txtNmPemilik.Value = rd.GetString(2)
Me.txtAlmtPerush.Value = rd.GetString(3)
Me.txttlpn.Value = rd.GetString(4)
Me.txtEmail.Value = rd.GetString(5)
Me.txtLamaPerush.Value = rd.GetString(6)
Me.txtJenis.Value = rd.GetString(7)
Me.txtSpesialisasi.Value = rd.GetString(8)
Me.txtkualitas.Value = rd.GetString(9)
Me.txtMerk.Value = rd.GetString(10)
Me.txtStandarPesanan.Value = rd.GetString(11)
Me.txtProduksi.Value = rd.GetString(12)
Me.txtlokal.Value = rd.GetString(13)
Me.txtnasional.Value = rd.GetString(14)
Me.txtekspor.Value = rd.GetString(15)
Me.txtpengalaman.Value = rd.GetString(16)
Me.txtlamaekspor.Value = rd.GetString(17)
Me.txtbiaya.Value = rd.GetString(18)
End While
Else
clearAll()
End If
rd.Close()
myConnection.close()
Catch SQLexc As SqlException
Response.Write("Open Failed. Error Details are: " & SQLexc.ToString())
End Try
End Sub
the source code to get the first parameter, the second to throw codingan parameters to form 2 and the third codingan to read in the form 2..I've tried but still can not

I would think that that code would produce an error, but you did not state that.
To add a parameter to the SQL statement:
Dim myCommand As New SqlCommand("SELECT COUNT(*) FROM kuesioner WHERE LTRIM(RTRIM(NmPerush)) = #param1", myConnection)
myCommand.Parameters.Add(New SqlParameter With {.ParameterName = "param1", _
.SqlDbType = SqlDbType.NVarChar, _
.Size = 200, _
.Value = sParam})
Please alter the .SqlDbType and .Size to match the definition in the database.

Related

asp.net vb Button.click insert to sql working at client but not working when move to server

This code is working a PC. I have filled grid view with the dataset, so I suppose I can read Excel.
However, the insert to sql part is not working when I copy the code to the server and I don't know why. It is not throwing any errors.
I removed the try catch lines but still, there are no errors.
I am adding new code block, I did a test and wrote a siple insert code like;
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim mysql_connection As New SqlConnection
mysql_connection.ConnectionString = "Data Source=SRV01;Initial Catalog=TR_Development;Persist Security Info=True;User ID=sa"
Dim command As String = "insert into gez_test (test) values ('c')"
Dim mysqlcommand As New SqlCommand
mysqlcommand.CommandType = CommandType.Text
mysqlcommand.CommandText = command
mysqlcommand.Connection = mysql_connection
If mysql_connection.State = ConnectionState.Closed Then mysql_connection.Open()
mysqlcommand.ExecuteNonQuery()
If mysql_connection.State = ConnectionState.Open Then mysql_connection.Close()
End Sub
And at server it is not inserting. What can be the problem any idea?
Orginal code
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim path_ As String = "\\exchange\COMPANY\web\" + FileUpload1.FileName
FileUpload1.PostedFile.SaveAs(path_)
Dim identifier As Boolean = False
Dim connStr As String = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path_ + "';Extended Properties=Excel 12.0;"
Dim MyConnection As OleDbConnection
Dim ds As DataSet
Dim MyCommand As OleDbDataAdapter
MyConnection = New OleDbConnection(connStr)
MyConnection.Open()
Dim dtSheets As DataTable = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
If sheet = "'BAS+Surcharges$'" Then
identifier = True
Exit For
End If
Next
If identifier = True Then
MyCommand = New OleDbDataAdapter("select * from [BAS+Surcharges$]", MyConnection)
ds = New System.Data.DataSet()
MyCommand.Fill(ds)
MyConnection.Close()
'**************SQL***************
Dim line, columns As Integer
line = ds.Tables(0).Rows.Count
columns = ds.Tables(0).Columns.Count
Label1.Text = line.ToString
ASPxTextBox1.Text = line.ToString
If line > 0 And columns = 16 Then
Dim command As String = "exec SP_INTRA_EXCEL_LINE_INSERT" _
+ " #line_isim, #nereden, #via, #nereye, #transit_sure, #baslangic_tarihi," _
+ "#e_kadar_gecerli, #kalem_kodu, #fiyatlandirma, #20DRY, #40DRY, #40HDRY," _
+ "#40HREF_NOR, #kayit_eden"
Dim mysql_connection As New SqlConnection
mysql_connection.ConnectionString = ConfigurationManager.ConnectionStrings("TR_DevelopmentConnectionString").ConnectionString
Dim mysqlcommand As New SqlCommand
mysqlcommand.CommandType = CommandType.Text
mysqlcommand.CommandText = command
mysqlcommand.Connection = mysql_connection
Dim line_isim, nereden, via, nereye, transit_sure, baslangic_tarihi, e_kadar_gecerli,
kalem_kodu, fiyatlandirma, _20DRY, _40DRY, _40HDRY,
_40HREF_NOR, kayit_eden As String
If mysql_connection.State = ConnectionState.Closed Then mysql_connection.Open()
For i = 6 To line - 1
line_isim = ds.Tables(0).Rows(i).Item(13).ToString
nereden = ds.Tables(0).Rows(i).Item(0).ToString
via = ds.Tables(0).Rows(i).Item(14).ToString
nereye = ds.Tables(0).Rows(i).Item(1).ToString
transit_sure = ds.Tables(0).Rows(i).Item(15).ToString
baslangic_tarihi = Convert.ToDateTime(ds.Tables(0).Rows(i).Item(2).ToString).ToString
e_kadar_gecerli = Convert.ToDateTime(ds.Tables(0).Rows(i).Item(3).ToString).ToString
kalem_kodu = ds.Tables(0).Rows(i).Item(7).ToString
fiyatlandirma = ds.Tables(0).Rows(i).Item(8).ToString
_20DRY = ds.Tables(0).Rows(i).Item(9).ToString
_40DRY = ds.Tables(0).Rows(i).Item(10).ToString
_40HDRY = ds.Tables(0).Rows(i).Item(11).ToString
_40HREF_NOR = ds.Tables(0).Rows(i).Item(12).ToString
kayit_eden = Environment.UserName.ToString
mysqlcommand.Parameters.AddWithValue("#line_isim", line_isim)
mysqlcommand.Parameters.AddWithValue("#nereden", nereden)
mysqlcommand.Parameters.AddWithValue("#via", via)
mysqlcommand.Parameters.AddWithValue("#nereye", nereye)
mysqlcommand.Parameters.AddWithValue("#transit_sure", transit_sure)
mysqlcommand.Parameters.AddWithValue("#baslangic_tarihi", baslangic_tarihi)
mysqlcommand.Parameters.AddWithValue("#e_kadar_gecerli", e_kadar_gecerli)
mysqlcommand.Parameters.AddWithValue("#kalem_kodu", kalem_kodu)
mysqlcommand.Parameters.AddWithValue("#fiyatlandirma", fiyatlandirma)
mysqlcommand.Parameters.AddWithValue("#20DRY", _20DRY)
mysqlcommand.Parameters.AddWithValue("#40DRY", _40DRY)
mysqlcommand.Parameters.AddWithValue("#40HDRY", _40HDRY)
mysqlcommand.Parameters.AddWithValue("#40HREF_NOR", _40HREF_NOR)
mysqlcommand.Parameters.AddWithValue("#kayit_eden", kayit_eden)
mysqlcommand.ExecuteNonQuery()
mysqlcommand.Parameters.Clear()
Next
If mysql_connection.State = ConnectionState.Open Then mysql_connection.Close()
End If
End If
ASPxGridView1.DataBind()

How to change row color in datagridview by comparing two columns from different tables using vb.net?

No success!
If user of tblcon with billmonth of tbltrns exists in tbltrns then highlight the rows of tblcon with red color
Code:
Private Sub checkexist()
For Each row As DataGridViewRow In DataGridView1.Rows
ConObj = New SqlConnection(ConStr)
ConObj.Open()
Dim qry As String = "SELECT * FROM tblTrns WHERE userName=#userName and bill_month=#bill_month"
CmdObj = New SqlCommand(qry, ConObj)
CmdObj.Parameters.AddWithValue("#bill_month", DateTimePicker1.Text)
CmdObj.Parameters.AddWithValue("#userName", (row.Cells("User").Value.ToString))
drObj = CmdObj.ExecuteReader()
If drObj.HasRows Then
row.DefaultCellStyle.BackColor = Color.Red
End If
Next
ConObj.Close()
End Sub
Query for the Grid
Public Function GetData() As DataView
ConObj = New SqlConnection(ConStr)
ConObj.Open()
CmdObj = New SqlCommand
dsObj = New DataSet
daObj = New SqlDataAdapter()
Dim SelectQry = "SELECT UserName[User],doj[Connection Date],packagename[Package],profilename[Profile],billing[Payment],fees[Fees],connectionstatus[Status] from TblCon"
CmdObj.CommandText = SelectQry
CmdObj.Connection = ConObj
daObj.SelectCommand = CmdObj
daObj.Fill(dsObj)
TvObj = dsObj.Tables(0).DefaultView
Return TvObj
ConObj.Close()
End Function
Query Changed in getdata but no success. Please guide ...........................................................................................................................................................................................................................................
Public Function GetData() As DataView
ConObj = New SqlConnection(ConStr)
ConObj.Open()
CmdObj = New SqlCommand
dsObj = New DataSet
daObj = New SqlDataAdapter()
Dim SelectQry = Dim SelectQry = "SELECT UserName[User],doj[Connection Date],packagename[Package],profilename[Profile],billing[Payment],fees[Fees],conn‌​‌​‌​ectionstatus[Status], (SELECT ISNULL(COUNT(*), 0) FROM tblTrns WHERE tblTrns.userName = tblCon.UserName AND bill_month = '" & DateTimePicker1.Text & "') [Comparison] from TblCon"
CmdObj.CommandText = SelectQry
CmdObj.Connection = ConObj
daObj.SelectCommand = CmdObj
daObj.Fill(dsObj)
TvObj = dsObj.Tables(0).DefaultView
Return TvObj
ConObj.Close()
End Function
I recommend you to fill a new column in your grid with a value for comparison and set it's visibility to false.
You can do that by a subselect or a left join on the second table (if you wish an example just post the query that fills your grid).
Based on your comparison column you can use the CellPainting event of the GridView. Like this:
Private Sub grdGridView_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles grdGridView.CellPainting
If e.RowIndex >= 0 Then
If grdGridView.Rows(e.RowIndex).Cells("colComparison").Value <> "0" And Not IsNothing(grdGridView.Rows(e.RowIndex).Cells("colComparison").Value) Then
e.CellStyle.BackColor = Color.OrangeRed
e.CellStyle.SelectionBackColor = Color.IndianRed
End If
End If
End Sub

DataGridView ScrollBar bug

When I get data for the DataGridView, my form freezes until the While loop completes, but then my scrollbar worked fine. I tried calling Application.DoEvents(); but that didn't work either.
If I get the data in a thread, then my form does not freeze, but the scrollbar disables and does not work after the While completes. I tried a BackgroundWorker but the scrollbar has a problem when using that too.
Private Sub dg()
myth = New Threading.Thread(AddressOf dgd)
myth.IsBackground = True
myth.Start()
End Sub
Private Sub dgd()
Dim x As Integer
If DataGridView1.Rows.Count = 0 Then x = 0 Else x = DataGridView1.Rows.Count
Try
Dim conn35a As New OleDbConnection("connstring")
Dim cmd35a As New OleDbCommand
cmd35a.CommandText = "Select count(*) from asd where downur Is Null"
cmd35a.CommandType = CommandType.Text
cmd35a.Connection = conn35a
conn35a.Open()
Dim returnValueaa As Integer = cmd35a.ExecuteScalar()
conn35a.Close()
Dim komut As String = "Select * from asd where downur Is Null"
Dim conn2 As New OleDbConnection("connstring")
conn2.Open()
Dim cmd2 As New OleDbCommand(komut, conn2)
Dim dr2 As OleDbDataReader = cmd2.ExecuteReader
If dr2.HasRows Then
While dr2.Read
Dim conn35 As New OleDbConnection("connstring")
Dim cmd35 As New OleDbCommand
cmd35.CommandText = "select count(*) from grid where ur = '" + dr2.Item("ur").ToString + "'"
cmd35.CommandType = CommandType.Text
cmd35.Connection = conn35
conn35.Open()
Dim returnValuea = cmd35.ExecuteScalar()
conn35.Close()
If returnValuea = 0 Then
DataGridView1.Rows.Add()
DataGridView1.Rows.Item(x).Cells(0).Value = x + 1
DataGridView1.Rows.Item(x).Cells(4).Value = "ID"
DataGridView1.Rows.Item(x).Cells(5).Value = dr2.Item("ur").ToString
DataGridView1.Rows.Item(x).Cells(6).Value = dr2.Item("ch").ToString
DataGridView1.Rows.Item(x).Cells(7).Value = dr2.Item("ti").ToString
DataGridView1.Rows.Item(x).Cells(8).Value = ".."
Dim client2 As New WebClient
Dim url As String = dr2.Item("pic").ToString
DataGridView1.Rows.Item(x).Cells(12).Value = New Bitmap(New MemoryStream(client2.DownloadData(url)))
DataGridView1.Rows.Item(x).Cells(13).Value = dr2.Item("vi")
DataGridView1.Rows.Item(x).Cells(14).Value = dr2.Item("su").ToString()
Dim con4 As New OleDbConnection("connstring")
con4.Open()
Dim cmd5 = New OleDbCommand("INSERT INTO grid (ur) VALUES (#ur)", con4)
cmd5.CommandType = CommandType.Text
cmd5.Parameters.Add("#ur", OleDbType.VarChar, 500).Value = dr2.Item("ur").ToString
cmd5.ExecuteNonQuery()
con4.Close()
x += 1
End If
End While
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I had the same problem.
I solved this by removing the Thread and calling the method directly

not taking all images after editing from data grid view in vb.net winform application

I am working on windows form application.
in cell content click i wrote code like this:
If e.ColumnIndex = 4 Then
Dim OFDLogo As New OpenFileDialog()
OFDLogo.Filter = "JPEG(*.jpg)|*.jpg|BMP(*.bmp)|*.bmp"
If OFDLogo.ShowDialog() = DialogResult.OK Then
gv.Rows(e.RowIndex).Cells(4).Value = Image.FromFile(OFDLogo.FileName)
End If
End If
and save button i wrote code like this:
Dim cmpny As String = "Delete from CompanyMaster_tbl"
Exetransaction(cmpny)
For i As Integer = 0 To gv.RowCount - 2
sqlInsertT2 = "Insert Into DepartmentMaster_tbl(dtname,dtphone,dtEmail,Cid) Values ('" + myTI.ToTitleCase(gv.Rows(i).Cells(1).Value) + "','" + gv.Rows(i).Cells(2).Value + "','" + gv.Rows(i).Cells(3).Value + "'," & Ccid & ");"
Exetransaction(sqlInsertT2)
Dim departmnt As String = gv.Rows(i).Cells(1).Value
Dim departid As Integer = RecordID("dtId", "DepartmentMaster_tbl", "dtName", departmnt)
Dim sql As String
'----------------------------------
Dim image As Image = TryCast(gv.Rows(i).Cells(4).Value, Image)
If image IsNot Nothing Then
Dim ms As New MemoryStream()
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
Dim imagedata As Byte() = ms.ToArray()
sql = "update DepartmentMaster_tbl set empimage=#photo where dtId='" & departid & "'"
Dim cmd As New SqlCommand(sql, con.connect)
cmd.Parameters.Add("#photo", SqlDbType.Image)
cmd.Parameters("#photo").Value = imagedata
cmd.ExecuteNonQuery()
con.disconnect()
End If
Next
in first time i can able to save all images form data grid view..but again i load the same page ,and i try to edit one image,,after that again i try save all images from data grid view..but thise time only saving edited image .i mean(that time thise line of code not working proper)
Dim image As Image = TryCast(gv.Rows(i).Cells(4).Value, Image)
In cell content click I am taking row_index..that s why happen
check this solution
Sub refreshgrid()
Dim cd As SqlCommandBuilder = New SqlCommandBuilder(adapter)
adapter = New SqlDataAdapter("select c.cid,c.CompanyName,d.dtId,d.dtName as Department,d.dtPhone as Phone,d.dtEmail as Email,d.empimage,0 as flag from CompanyMaster_tbl c join DepartmentMaster_tbl d on c.Cid=d.cId order by cid", con.connect)
dt1 = New DataTable
bSource = New BindingSource
adapter.Fill(dt1) 'Filling dt with the information from the DB
bSource.DataSource = dt1
gv.DataSource = bSource
gv.Columns("cid").Visible = False
gv.Columns("dtId").Visible = False
Dim img As New DataGridViewImageColumn
img.HeaderText = "Image"
gv.Columns.Insert(6, img)
For i As Integer = 0 To gv.Rows.Count - 1
gv.Rows(i).Cells(6).Value = gv.Rows(i).Cells(7).Value
Next
gv.Columns("empimage").Visible = False
For i As Integer = 0 To gv.Rows.Count - 2
If Not IsDBNull(gv.Rows(i).Cells(6).Value) Then
gv.Rows(i).Height = 75
Dim column As DataGridViewColumn = gv.Columns(6)
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
End If
Next
GenerateUniqueData(1)
End Sub
Private Sub btnupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnupdate.Click
adapter = New SqlDataAdapter()
Dim cid As Integer
Dim dtid As Integer
Dim cmpname As String
Dim dtname As String
Dim dtPhone As String
Dim dtEmail As String
Dim dtimage As Image
For i As Integer = 0 To gv.RowCount - 2
' Dim rv = DirectCast(bSource.Current, DataRowView)
If (gv.Rows(i).Cells(8).Value = 1) Then
Dim rv = DirectCast(gv.Rows(i).DataBoundItem, DataRowView)
cid = rv.Row.Field(Of Integer)("Cid")
dtid = rv.Row.Field(Of Integer)("dtId")
cmpname = rv.Row.Field(Of String)("CompanyName")
dtname = rv.Row.Field(Of String)("Department")
dtPhone = rv.Row.Field(Of String)("Phone")
dtEmail = rv.Row.Field(Of String)("Email")
'Using ms As New MemoryStream(rv.Row.Field(Of Byte())("empimage"))
' dtimage = New Bitmap(ms)
'End Using
adapter.UpdateCommand = New SqlCommand("UPDATE CompanyMaster_tbl SET CompanyName = #CompanyName", con.connect)
'this code for updating image also..
adapter.UpdateCommand = New SqlCommand("update DepartmentMaster_tbl set dtName = #dtName,dtPhone = #dtPhone,dtEmail = #dtEmail,empimage=#dtimage where dtId=#dtid", con.connect)
' adapter.UpdateCommand = New SqlCommand("update DepartmentMaster_tbl set dtName = #dtName,dtPhone = #dtPhone,dtEmail = #dtEmail where dtId=#dtid", con.connect)
adapter.UpdateCommand.Parameters.AddWithValue("#Cid", cid)
adapter.UpdateCommand.Parameters.AddWithValue("#CompanyName", cmpname)
adapter.UpdateCommand.Parameters.AddWithValue("#dtId", dtid)
adapter.UpdateCommand.Parameters.AddWithValue("#dtName", dtname)
adapter.UpdateCommand.Parameters.AddWithValue("#dtPhone", dtPhone)
adapter.UpdateCommand.Parameters.AddWithValue("#dtEmail", dtEmail)
'Dim md As New MemoryStream()
'dtimage.Save(md, System.Drawing.Imaging.ImageFormat.Gif)
' Dim imagedata As Byte() = md.ToArray()
'Dim md As New MemoryStream()
'' Save to memory using the Jpeg format
'dtimage.Save(md, ImageFormat.Gif)
' read to end
'Dim bmpBytes As Byte() = md.GetBuffer()
' Dim image As Byte() = System.IO.File.ReadAllBytes()
Dim image As Image = TryCast(gv.Rows(i).Cells(6).Value, Image)
If image IsNot Nothing Then
Dim ms As New MemoryStream()
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
Dim imagedata As Byte() = ms.ToArray()
adapter.UpdateCommand.Parameters.AddWithValue("#dtimage", imagedata)
End If
'adapter.UpdateCommand.Parameters.AddWithValue("#dtimage", dtimage)
adapter.UpdateCommand.ExecuteNonQuery()
End If
Next
End Sub
Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclose.Click
Me.Close()
End Sub
Private Sub gv_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gv.CellContentClick
If e.ColumnIndex = 6 Then
Dim OFDLogo As New OpenFileDialog()
OFDLogo.Filter = "JPEG(*.jpg)|*.jpg|BMP(*.bmp)|*.bmp"
If OFDLogo.ShowDialog() = DialogResult.OK Then
gv.Rows(e.RowIndex).Cells(6).Value = Image.FromFile(OFDLogo.FileName)
gv.Rows(e.RowIndex).Cells(8).Value = "1"
End If
End If
End Sub
Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click
For i As Integer = 0 To gv.RowCount - 2
If gv.Rows(i).Cells(1).Value.ToString.Length <> 0 AndAlso Not IsDBNull(gv.Rows(i).Cells(1).Value) Then
If gv.Rows(i).Cells(3).Value.ToString.Length = 0 OrElse IsDBNull(gv.Rows(i).Cells(3).Value) Then
MsgBox("Please Enter Department Details")
Exit Sub
End If
End If
Next
'Dim deprt As String = "Delete from DepartmentMaster_tbl"
'Exetransaction(deprt)
'Dim cmpny As String = "Delete from CompanyMaster_tbl"
'Exetransaction(cmpny)
Dim sqlInsertT1 As String = ""
Dim sqlInsertT2 As String = ""
For i As Integer = 0 To gv.RowCount - 2
' If gv.Rows(i).Cells(1).Value IsNot System.DBNull.Value AndAlso gv.Rows(i).Cells(1).Value <> "" Then
If (gv.Rows(i).Cells(8).Value = 1) Then
If Not IsDBNull(gv.Rows(i).Cells(1).Value) AndAlso gv.Rows(i).Cells(1).Value.ToString.Length <> 0 Then
Dim cnt As Integer = RecordPresent("CompanyMaster_tbl", "CompanyName", gv.Rows(i).Cells(1).Value)
If cnt = 0 Then
sqlInsertT1 = "Insert Into CompanyMaster_tbl(CompanyName) Values ('" + myTI.ToTitleCase(gv.Rows(i).Cells(1).Value) + "')"
Exetransaction(sqlInsertT1)
Ccid = RecordID("Cid", "CompanyMaster_tbl", "CompanyName", gv.Rows(i).Cells(1).Value)
Else
Ccid = RecordID("Cid", "CompanyMaster_tbl", "CompanyName", gv.Rows(i).Cells(1).Value)
End If
End If
If Not IsDBNull(gv.Rows(i).Cells(3).Value) AndAlso gv.Rows(i).Cells(3).Value.ToString.Length <> 0 Then
sqlInsertT2 = "Insert Into DepartmentMaster_tbl(dtname,dtphone,dtEmail,Cid) Values ('" + myTI.ToTitleCase(gv.Rows(i).Cells(3).Value) + "','" + gv.Rows(i).Cells(4).Value + "','" + gv.Rows(i).Cells(5).Value + "'," & Ccid & ");"
Exetransaction(sqlInsertT2)
Dim departmnt As String = gv.Rows(i).Cells(3).Value
Dim departid As Integer = RecordID("dtId", "DepartmentMaster_tbl", "dtName", departmnt)
Dim sql As String
'----------------------------------
Dim image As Image = TryCast(gv.Rows(i).Cells(6).Value, Image)
If image IsNot Nothing Then
Dim ms As New MemoryStream()
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
Dim imagedata As Byte() = ms.ToArray()
sql = "update DepartmentMaster_tbl set empimage=#photo where dtId='" & departid & "'"
Dim cmd As New SqlCommand(sql, con.connect)
cmd.Parameters.Add("#photo", SqlDbType.Image)
cmd.Parameters("#photo").Value = imagedata
cmd.ExecuteNonQuery()
con.disconnect()
End If
End If
End If
Next
' refreshgrid()
End Sub

How can I solve "Must declare the scalar variable #cds" sql?

For the last three hours. I searched the internet for solutions to my problem. I found some but none of them worked (!?). The error is in the btnAdd Sub. I couldn't use this form of declaration: 'DECLARE #cds SqlDBType.SmallInt because I would get the following error: Statement is not valid inside a method/multiline lambda. I also used their form of declaration http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.insertcommand%28v=vs.110%29.aspx but again... I receive the same error. The commented sections are everything I tried. Maybe you can help me solve this. :)
Updated correct solution:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
con.Open()
Dim dr As DataRow
mycmd.CommandText = "insert into studenti(cods, nrmatricol, nume, grupa, datan) values(#cs,#nm,#n,#g,#dn)"
Dim p1 As New SqlParameter
Dim p2 As New SqlParameter
Dim p3 As New SqlParameter
Dim p4 As New SqlParameter
Dim p5 As New SqlParameter
mycmd.Parameters.Clear()
p1.ParameterName = "#cs"
p1.Value = Convert.ToInt16(txtCodS.Text)
mycmd.Parameters.Add(p1)
p2.ParameterName = "#nm"
p2.Value = txtNrMat.Text
mycmd.Parameters.Add(p2)
p3.ParameterName = "#n"
p3.Value = txtNume.Text
mycmd.Parameters.Add(p3)
p4.ParameterName = "#g"
p4.Value = txtGrupa.Text
mycmd.Parameters.Add(p4)
p5.ParameterName = "#dn"
p5.Value = Convert.ToDateTime(txtDataN.Text)
mycmd.Parameters.Add(p5)
mycmd.Connection = con
da1.InsertCommand = mycmd
dr = DataSet1.Tables("studenti").NewRow()
dr("cods") = Convert.ToInt16(txtCodS.Text)
dr("nrmatricol") = txtNrMat.Text
dr("nume") = txtNume.Text
dr("grupa") = txtGrupa.Text
dr("datan") = Convert.ToDateTime(txtDataN.Text)
DataSet1.Tables("studenti").Rows.Add(dr)
da1.Update(DataSet1, "studenti")
UpdateUI()
con.Close()
End Sub
Wrong:
Dim da1 As New SqlClient.SqlDataAdapter
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
con.Open()
Dim dr As DataRow
Dim mycmd As New SqlClient.SqlCommand
//Dim mycmd2 As New SqlClient.SqlCommand
//mycmd2.Connection = con
// mycmd2.CommandText = "select* from studenti"
//Dim v(4) As Object
//v(0) = Convert.ToInt16(txtCodS.Text)
//v(1) = txtNrMat.Text
//v(2) = txtNume.Text
//v(3) = txtGrupa.Text
// v(4) = txtDataN.Text
mycmd.CommandText = "insert into studenti (cods,nrmatricol,nume,grupa,datan) values (#cds,#nm,#n,#g,#dn)"
Dim p1 As New SqlClient.SqlParameter
p1.ParameterName = "#cds"
p1.Value = Convert.ToInt16(txtCodS.Text)
//DECLARE #cds SqlDBType.SmallInt
//cmd.Parameters.Clear()
cmd.Parameters.Add(p1)
//cmd.Parameters.Add("#cds", SqlDbType.SmallInt).Value = Convert.ToInt16(txtCodS.Text)
cmd.Parameters.Add("#nm", SqlDbType.VarChar, 10)
cmd.Parameters.Add("#n", SqlDbType.VarChar, 30)
cmd.Parameters.Add("#g", SqlDbType.VarChar, 10)
cmd.Parameters.Add("#dn", SqlDbType.DateTime)
mycmd.Connection = con
da1.InsertCommand = mycmd
dr = DataSet1.Tables("studenti").NewRow()
dr("cods") = Convert.ToInt16(txtCodS.Text)
dr("nrmatricol") = txtNrMat.Text
dr("nume") = txtNume.Text
dr("grupa") = txtGrupa.Text
dr("datan") = Convert.ToDateTime(txtDataN.Text)
DataSet1.Tables("studenti").Rows.Add(dr)
da1.Update(DataSet1, "studenti")
UpdateUI()
con.Close()
End Sub
End Class
#cds variable is set by after that it is removed by cmd.Parameters.Clear().
Just remove this line of code and provide a value for #cds.