How to change row color in datagridview by comparing two columns from different tables using vb.net? - 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

Related

Read from two tables information

How can i convert this code to read information from the two tables.
Private Sub GenerateDynamicUserControl()
FlowLayoutPanel1.Controls.Clear()
Dim dt As DataTable = New ClassBLL().GetItems()
If dt IsNot Nothing Then
If dt.Rows.Count > 0 Then
Dim listItems As ListItem() = New ListItem(dt.Rows.Count - 1) {}
For i As Integer = 0 To 1 - 1
For Each row As DataRow In dt.Rows
Dim listItem As New ListItem()
listItems(i) = listItem
'Dim ms As New MemoryStream(CType(row("userPic"), Byte()))
listItems(i).Width = FlowLayoutPanel1.Width - 30
listItems(i).Icon = orderPicFromString
listItems(i).Icon2 = orderPicFromString2
listItems(i).OrderFrom = row("orderfrom").ToString()
listItems(i).OrderTitle = orderTitleString
listItems(i).OrderReceiver = row("orderreceiver").ToString()
listItems(i).OrderTitle2 = orderTitleString2
'listItems(i).ButtonBackground = orderButtonBackString
listItems(i).ButtonText = row("orderstatus").ToString()
listItems(i).OrderDate = row("orderdate")
listItems(i).IDOrder = row("orderid").ToString()
If listItems(i).ButtonText = "Accepted" Then
listItems(i).ButtonBackground = Color.FromArgb(26, 168, 92)
ElseIf listItems(i).ButtonText = "Declined" Then
listItems(i).ButtonBackground = Color.FromArgb(246, 50, 90)
ElseIf listItems(i).ButtonText = "Proceed" Then
listItems(i).ButtonBackground = Color.FromArgb(255, 174, 33)
ElseIf listItems(i).ButtonText = "Waiting" Then
listItems(i).ButtonBackground = Color.FromArgb(53, 121, 255)
Else
listItems(i).ButtonBackground = Color.FromArgb(91, 146, 255)
End If
FlowLayoutPanel1.Controls.Add(listItems(i))
Next
Next
End If
End If
End Sub
So let me start with information about this that is in RED , i need to get this information from another table that is called "Profiles"
listItems(i).Icon = orderPicFromString
listItems(i).Icon2 = orderPicFromString2
listItems(i).OrderTitle = orderTitleString
listItems(i).OrderTitle2 = orderTitleString2
So this fields i need to read them from table "Profiles"
So next is as you see the code up calls Class GetItems:
Public Function GetItems() As DataTable
Try
Dim objdal As New ClassDAL()
Return objdal.ReadItemsTable()
Catch e As Exception
Dim result As DialogResult = MessageBox.Show(e.Message.ToString())
Return Nothing
End Try
End Function
Public Function ReadItemsTable() As DataTable
Using cons As New OleDbConnection(ServerStatus)
Using cmd As New OleDbCommand()
cmd.Connection = cons
cmd.CommandText = "SELECT * FROM OrdersAssigned ORDER BY ID ASC"
cons.Open()
Using sda As New OleDbDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
So this is main function to display the results from row("name")
Then i try to create like this:
'Declare Strings for OrderDisplay
Public orderFromString As String
Public orderTitleString As String
Public orderReceiveString As String
Public orderTitleString2 As String
Public orderButtonBackString As Color
Public orderButtonTextString As String
Public orderDateString As Date
Public orderIDString As String
Public orderPicFromString As Image
Public orderPicFromString2 As Image
'Get Accounts Name
Public orderAccountFrom As String
Public orderAccountTo As String
Public Sub GetUserPictureFrom()
Using conn As New OleDbConnection(ServerStatus)
conn.Open()
Dim sql As String = "Select userPicture From Profiles where userAccount=#GetLogin"
Using cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#GetLogin", orderAccountFrom)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If imageData IsNot Nothing Then
Using stream As New MemoryStream(imageData)
Dim backgroundImage As Image = Image.FromStream(stream)
orderPicFromString = backgroundImage
End Using
End If
End Using
End Using
End Sub
Public Sub GetUserPictureTo()
Using conn As New OleDbConnection(ServerStatus)
conn.Open()
Dim sql As String = "Select userPicture From Profiles where userAccount=#GetLogin"
Using cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#GetLogin", orderAccountTo)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If imageData IsNot Nothing Then
Using stream As New MemoryStream(imageData)
Dim backgroundImage As Image = Image.FromStream(stream)
orderPicFromString2 = backgroundImage
End Using
End If
End Using
End Using
End Sub
Public Sub GetOrdersDisplay()
Using cons As New OleDbConnection(ServerStatus)
Using cmd As New OleDbCommand()
cmd.Connection = cons
cmd.CommandText = "SELECT * FROM OrdersAssigned ORDER BY ID ASC"
cons.Open()
Using rdr As OleDbDataReader = cmd.ExecuteReader()
While rdr.Read()
orderAccountFrom = rdr("orderacc").ToString
orderAccountTo = rdr("orderreceiveracc").ToString
End While
End Using
cmd.CommandText = "Select userPosition From Profiles where userAccount = #GetUser"
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#GetUser", orderAccountFrom)
Using rds As OleDbDataReader = cmd.ExecuteReader()
While rds.Read()
orderTitleString = rds("userPosition").ToString
End While
End Using
cmd.CommandText = "Select userPosition From Profiles where userAccount = #ToUser"
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#ToUser", orderAccountTo).ToString()
Using rdx As OleDbDataReader = cmd.ExecuteReader()
While rdx.Read()
orderTitleString2 = rdx("userPosition").ToString
End While
End Using
End Using
End Using
GetUserPictureFrom()
GetUserPictureTo()
End Sub
What it needs to do is:
orderAccountFrom = rdr("orderacc").ToString
orderAccountTo = rdr("orderreceiveracc").ToString
will get the accounts from table OrdersAssigned and search with them in table Profiles to get results userPosition
What means this
userx in Profiles has userPosition = Boss
usery in Profiles has userPosition = Worker
i want to fetch this information.
The same goes for the pictures each user has his own picture.
How can i manage to fix this issue so to get correct data?
How can i combine all of this inside the function ReadItemsTable() it would be better to be in one place everything so
listItems(i).Icon = orderPicFromString
listItems(i).Icon2 = orderPicFromString2
listItems(i).OrderTitle = orderTitleString
listItems(i).OrderTitle2 = orderTitleString2
to work correct to get information
cmd.CommandText = "SELECT OrdersAssigned.*,
ProfilesFrom.userPosition AS UserPositionFrom,
ProfilesFrom.userPicture AS UserPictureFrom,
ProfilesTo.userPosition AS UserPositionTo,
ProfilesTo.userPicture AS UserPictureTo
FROM
(OrdersAssigned
LEFT OUTER JOIN Profiles AS ProfilesFrom ON OrdersAssigned.orderacc = ProfilesFrom.userAccount)
LEFT OUTER JOIN Profiles AS ProfilesTo ON OrdersAssigned.orderreceiveracc = ProfilesTo.userAccount
ORDER BY
OrdersAssigned.ID ASC;"

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()

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

Copy a row to another DataGridView

I have two DataGridViews in Windows Form, VB.NET
When I double click on the FullSelectedRow of DataGridView1, the SelectedRow should be copied to the DataGridView2, both grids are DataBounded from SQL Server 2008..
Here is my code to retrieve the data in each grid..
**DataGridView1**
Dim UserScheduleString As String = "SELECT * FROM Schedule"
Dim UserScheduleStringList As New SqlCommand(UserScheduleString, mdl_Connection.CONN)
UserScheduleStringList.CommandType = CommandType.Text
UserScheduleStringListAdpt.SelectCommand = UserScheduleStringList
UserScheduleStringListAdpt.SelectCommand.ExecuteNonQuery()
UserScheduleStringListAdpt.Fill(UserScheduleStringListDataSet, "Users")
DataGridView1.DataSource = UserScheduleStringListDataSet.Tables("Users")
**DataGridView2**
Dim SomeTableString As String = "SELECT * FROM someTable"
Dim SomeTableStringList As New SqlCommand(SomeTableString, mdl_Connection.CONN)
SomeTableStringList.CommandType = CommandType.Text
SomeTableStringListAdpt.SelectCommand = SomeTableStringList
SomeTableStringListAdpt.SelectCommand.ExecuteNonQuery()
SomeTableStringListAdpt.FillSomeTableStringListDataSet, "*<tablename>*")
DataGridView1.DataSource = SomeTableStringListDataSet.Tables("*<tablename>*")
I've search over other forums and this is what I've got..
newCustomersRow = UserScheduleStringListDataSet.Tables("Users").NewRow()
newCustomersRow("ID") = "0023"
newCustomersRow("Day") = "Tuesday"
newCustomersRow("Start Time") = "13:00:00"
newCustomersRow("End Time") = "18:00:00"
UserScheduleStringListDataSet.Tables("Users").Rows.Add(newCustomersRow)
UserScheduleStringListAdpt.Update(UserScheduleStringListDataSet, "Users")
When I try to put this in DataGridView1_CellMouseDoubleClick, it gives me an error of Object reference not set to an instance of an object.
Try the following:
Private Sub DataGridView1_CellMouseDoubleClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
Dim dr = DirectCast(DataGridView1.Rows(e.RowIndex).DataBoundItem, System.Data.DataRowView).Row
UserScheduleStringListDataSet.Tables("Users").ImportRow(dr)
UserScheduleStringListAdpt.Update(UserScheduleStringListDataSet, "Users")
End Sub

VB.NET DataSet Update

Why my set of codes didn't update in DataSet? Then it goes to Error. Please anyone check this code and point me out where I am missing. Thanks in advance!
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=username;Password=pwds")
Dim dadPurchaseInfo As New SqlDataAdapter
Dim dsPurchaseInfo As New DataSet1
Try
Dim dRow As DataRow
conxMain.Open()
Dim cmdSelectCommand As SqlCommand = New SqlCommand("SELECT * FROM Stock", conxMain)
cmdSelectCommand.CommandTimeout = 30
dadPurchaseInfo.SelectCommand = cmdSelectCommand
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo)
dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")
For Each dRow In dsPurchaseInfo.Tables("Stock").Rows
If CInt(dRow.Item("StockID").ToString()) = 2 Then
dRow.Item("StockCode") = "Re-Fashion[G]"
End If
Next
dadPurchaseInfo.Update(dsPurchaseInfo, "Stock")
Catch ex As Exception
MsgBox("Error : ")
Finally
If dadPurchaseInfo IsNot Nothing Then
dadPurchaseInfo.Dispose()
End If
If dsPurchaseInfo IsNot Nothing Then
dsPurchaseInfo.Dispose()
End If
If conxMain IsNot Nothing Then
conxMain.Close()
conxMain.Dispose()
End If
End Try
End Sub
Does your condition in the loop get executed (set a break point!)? Where is the error thrown? What error?
Also, why does it use ToString at all? This seems redundant.
If CInt(dRow.Item("StockID")) = 2 Then
Should be enough.
Finally, you’re performing redundant cleanup:
If conxMain IsNot Nothing Then
conxMain.Close()
conxMain.Dispose()
End If
Dispose implies Close – no need to perform both operations:
Close and Dispose are functionally equivalent.
[Source: MSDN]
Does your dataAdapter has update command ?
(it looks like it doesn't - so it doesn't know what do to with update....)
Here is an Update Command example:(for an employee table with 3 columns - as listed below:
UPDATE [Employee]
SET [name] = #name
, [manager] = #manager
WHERE (([id] = #Original_id) AND
((#IsNull_name = 1 AND [name] IS NULL) OR
([name] = #Original_name)) AND
((#IsNull_manager = 1 AND [manager] IS NULL) OR
([manager] = #Original_manager)));
SELECT id
, name
, manager
FROM Employee
WHERE (id = #id)
You can see it is a general update that can handle changes in any field.
I got it from the error correction of my program by Konard Rudolph!
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=username;Password=pwds")
Dim dadPurchaseInfo As New SqlDataAdapter
Dim dsPurchaseInfo As New DataSet1
Try
Dim dRow As DataRow
conxMain.Open()
dadPurchaseInfo.SelectCommand = New SqlCommand("SELECT * FROM Stock", conxMain)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo)
dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")
For Each dRow In dsPurchaseInfo.Tables("Stock").Rows
If CInt(dRow.Item("StockID")) = 2 Then
dRow.Item("StockCode") = "Re-Fashion(H)"
End If
Next
dadPurchaseInfo.Update(dsPurchaseInfo, "Stock")
Catch ex As Exception
MsgBox("Error : " & vbCrLf & ex.Message)
Finally
If dadPurchaseInfo IsNot Nothing Then
dadPurchaseInfo.Dispose()
End If
If dsPurchaseInfo IsNot Nothing Then
dsPurchaseInfo.Dispose()
End If
If conxMain IsNot Nothing Then
conxMain.Dispose()
End If
End Try
End Sub
The above set of code work to update with DataSet! Thanks to stackoverflow community and who answered my question.
Here is ref:
How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual Basic .NET
How to update a database from a DataSet object by using Visual Basic .NET
p.s: Like o.k.w said : The Table must have primary key. Thanks o.k.w!
--MENU--
Dim login As New LoginClass
login.ShowDialog()
--CONEXION--
Private conec As SqlConnection
Dim stringCon As String = "Data Source= ;Initial Catalog=;Persist Security Info=True;User ID=;Password="
Public ReadOnly Property prConec() As Object
Get
Return conec
End Get
End Property
Public Sub Conectar()
Try
conec = New SqlConnection(stringCon)
If conec.State <> ConnectionState.Open Then
conec.Open()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
--BUSCAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_cliente", funciones.prConec)
Dim dt As New DataTable
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("#i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "B"
dt.Load(coman.ExecuteReader())
grdClientes.DataSource = dt
--INSERTAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_articulo", funciones.prConec)
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("#i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "I"
coman.ExecuteNonQuery()
Buscar()
Limpiar()
--COMBO--
Dim dt As New DataTable
dt.Columns.Add("Codigo")
dt.Columns.Add("Descripcion")
Dim dr1 As DataRow = dt.NewRow
dr1.Item("Codigo") = "A"
dr1.Item("Descripcion") = "Activo"
dt.Rows.Add(dr1)
Dim dr2 As DataRow = dt.NewRow
dr2.Item("Codigo") = "I"
dr2.Item("Descripcion") = "Inactivo"
dt.Rows.Add(dr2)
cmbEstado.DataSource = dt
cmbEstado.ValueMember = "Codigo"
cmbEstado.DisplayMember = "Descripcion"
--GRIDVIEW--
--1--
Dim grdFila As DataGridViewRow = grdClientes.CurrentRow
txtCedula.Text = grdFila.Cells(0).Value
--2--
If DataGridProductos.CurrentCell.ColumnIndex = 0 Then
Dim FLstArticulos As New FLstArticulos
FLstArticulos.ShowDialog()
DataGridProductos.CurrentRow.Cells(0).Value = FLstArticulos.PrIdArticulo
End If
--GRIDVIEW.CELLENDEDIT--
If DataGridProductos.CurrentCell.ColumnIndex = 3 Then
Dim precio As New Double
Dim cantidad As New Double
precio = CDbl(grdRow.Cells(2).Value)
cantidad = CDbl(grdRow.Cells(3).Value)
DataGridProductos.CurrentRow.Cells(4).Value = PLTotalFilaItem(cantidad, precio)
PLCargaTotales()
End If
Sub PLCargaTotales()
Dim subTotal As Double
Dim iva As Double
For Each grd As DataGridViewRow In DataGridProductos.Rows
If Not String.IsNullOrEmpty(grd.Cells(4).Value) Then
subTotal = subTotal + CDbl(grd.Cells(4).Value)
End If
Next grd
txtSubtotal.Text = subTotal.ToString
iva = Decimal.Round(subTotal`enter code here` * 0.12)
txtIva.Text = iva.ToString
txtTotalPagar.Text = (subTotal + iva).ToString
End Sub