Moving rows up and down in a datagridview and updating the database - vb.net

I have a datagridview and I am getting all the data from a sql database I want to be able to move rows from one position to the other either up or down and it should also reflect the same in the database.
Currently this is what I have done and it does move the items as desired ( am adding 100 to the value of the column that am using to move up and subtracting 100 when moving down) but the problem with this is that if it find that the value of the next item in the row is lower, it doesnt move or if you add 100 then its value suddenly becomes more that 3 items above it, it doesnt move to the next position instead it moves 3 positions up, how can I simplify it to make it move just 1 row above or below respectively.
Private Sub BntMoveUp_Click(sender As Object, e As EventArgs) Handles BntMoveUp.Click
For i As Integer = 0 To DataGridView2.Rows.Count() - 1
Dim c As Boolean
c = DataGridView2.Rows(i).Cells(0).Value
' if the checkbox cell is checked
If c = True Then
' MessageBox.Show("Checked")
Dim cid As Integer = DataGridView2.Rows(i).Cells(1).Value
Dim cid2 As Integer = DataGridView2.Rows(i - 1).Cells(1).Value
Str = "update Production..CMBGSeat_Staging set [Priority] =[Priority] > 1 where cid=" & cid
updaterecords(Str)
Dim cmd As Odbc.OdbcCommand
Dim LDataadapter As Odbc.OdbcDataAdapter
Dim MyDataset As DataSet
Dim insert As String
con()
insert = "select * from Production..CMBGSeat_Staging where DateCompleted is null order by Priority desc"
cmd = New Odbc.OdbcCommand(insert, sqlcon)
LDataadapter = New Odbc.OdbcDataAdapter
LDataadapter.SelectCommand = cmd
MyDataset = New DataSet
' MyDataset = New DataSet
LDataadapter.Fill(MyDataset)
DataGridView2.DataSource = MyDataset.Tables(0)
' if not
Else
' MessageBox.Show("Not Checked")
End If
Next
End Sub
Private Sub BtnMoveDown_Click(sender As Object, e As EventArgs) Handles BtnMoveDown.Click
For i As Integer = 0 To DataGridView2.Rows.Count() - 1
Dim c As Boolean
c = DataGridView2.Rows(i).Cells(0).Value
'If the Then checkbox cell Is checked
If c = True Then
' MessageBox.Show("Checked")
Dim cid As Integer = DataGridView2.Rows(i).Cells(1).Value
Dim cid2 As Integer = DataGridView2.Rows(i + 1).Cells(1).Value
Str = "update Production..CMBGSeat_Staging set [Priority] =[Priority] < 1 where cid=" & cid
updaterecords(Str)
Dim cmd As Odbc.OdbcCommand
Dim LDataadapter As Odbc.OdbcDataAdapter
Dim MyDataset As DataSet
Dim insert As String
con()
insert = "select * from Production..CMBGSeat_Staging where DateCompleted is null order by Priority desc"
cmd = New Odbc.OdbcCommand(insert, sqlcon)
LDataadapter = New Odbc.OdbcDataAdapter
LDataadapter.SelectCommand = cmd
MyDataset = New DataSet
MyDataset = New DataSet
LDataadapter.Fill(MyDataset)
DataGridView2.DataSource = MyDataset.Tables(0)
' if not
Else
'MessageBox.Show("Not Checked")
End If
Next
End Sub

Related

DataGridView moves rows to bottom when cell is updated with Unbound data

I have a DataGridView that is styled with code and is using data from a SQLite Database
The Database is NOT bound to the DataGridView. A number of events are triggered when I click on a row.
First the Database is updated with today's date.
And the cell that contain's that date reflects the change.
I then call a sort on the column based on the cells value. With this code
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
The process works as expected with no issues IF I omit these lines of code from the Sub Routine ViewSearches() that populates the DataGridView.
If rowCount <= 25 Then
maxRowCount = 25 - rowCount
For iA = 1 To maxRowCount
dgvLinks.Rows.Add(" ")
Next
End If
I can use these empty rows if I make a call to repopulate the DataGridView with ViewSearches()
I am trying to avoid this design as it seems like a over use of resource.
The ERROR that is happening is the 4 rows that contain data are moved to the bottom of the DataGridView and above these 4 rows with data are the empty rows. I will post the relevant code below.
My question How can I keep the empty rows and populate DataGridView so the rows with data are at the top of the DataGridView?
Here is a Screen Shot after I selected LID 2. It is updated and bubbled to the bottom of the DGV.
Private Sub ViewSearches()
Dim intID As Integer
Dim strChannelName As String
Dim strLinkAddress As String
Dim strLastVisit As String
Dim strLinkType As String
Dim rowCount As Integer
Dim maxRowCount As Integer
'Dim emptyStr As String = " "
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand("", conn)
'cmd.CommandText = "SELECT * FROM LinkTable"
' Line of CODE Above works with If statement in While rdr
'==========================================================
'cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = 'News'"
cmd.CommandText = "SELECT * FROM LinkTable WHERE ytSiteType = #site"
cmd.Parameters.Add("#site", DbType.String).Value = gvSLT
Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
'dgvLinks.DataSource = rdr
'Statement Above use when DB is bound to dgvLinks
'=================================================
While rdr.Read()
intID = CInt((rdr("LID")))
strChannelName = rdr("ytChannelName").ToString
strLinkAddress = rdr("ytLinkAddress").ToString
strLastVisit = rdr("ytLastVisit").ToString
strLinkType = rdr("ytSiteType").ToString
'If strLinkType = gvSLT Then
dgvLinks.Rows.Add(intID, strChannelName, strLinkAddress, strLastVisit)
rowCount = rowCount + 1
'End If
End While
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
End Using
If rowCount <= 25 Then
maxRowCount = 25 - rowCount
For iA = 1 To maxRowCount
dgvLinks.Rows.Add(" ")
Next
End If
End Using
End Using
'FindEmpty()
End Sub
Click Event with Update to Database
Private Sub dgvLinks_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvLinks.CellClick
selRow = e.RowIndex
If e.RowIndex = -1 Then
gvalertType = "4"
frmAlert.ShowDialog()
Exit Sub
End If
'Dim col As DataGridViewColumn = Me.dgvLinks.Columns(e.ColumnIndex)
Dim row As DataGridViewRow = Me.dgvLinks.Rows(e.RowIndex)
If row.Cells(2).Value Is Nothing Then
gvalertType = "5"
frmAlert.ShowDialog()
Return
Exit Sub
ElseIf gvTxType = "View" Then
webPAGE = row.Cells(2).Value.ToString()
siteID = CInt(row.Cells(0).Value.ToString())
UpdateSiteData()
''MsgBox("Stop " & selRow)
'dgvLinks.ClearSelection()
'dgvLinks.Refresh()
'dgvLinks.RefreshEdit()
Process.Start(webPAGE)
'dgvLinks.Columns.Clear()
''dgvLinks.Rows.Clear()
''ViewSearches()
ElseIf gvTxType = "Delete" Or gvTxType = "Update" Then
gvID = CInt(row.Cells(0).Value)
gvSiteName = row.Cells(1).Value.ToString
gvSiteURL = row.Cells(2).Value.ToString
frmADE.Show()
Close()
End If
End Sub
Update Routine
Public Sub UpdateSiteData()
Dim dateToday = Date.Today
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 ytLastVisit = #ytLastVisit WHERE LID =" & siteID, conn)
conn.Open()
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.ExecuteNonQuery()
dgvLinks.Rows(selRow).Cells(3).Value = dateToday.ToString("M-d-yyyy")
'Line of code above INSERTS value in Last Visit Column at the correct ROW
'NOT needed if you reload data from the database
'=========================================================================
'dgvLinks.Refresh()
'dgvLinks.RefreshEdit()
dgvLinks.Sort(dgvLinks.Columns(3), ListSortDirection.Ascending)
End Using
End Sub
You will see a number of things I have tried commented out.
As I said I can FIX the issue if I make a call to the ViewSearches() Sub Routine.
Private Sub StyleDGV()
'Sets Design of the DataGridView
'===============================
dgvLinks.DefaultCellStyle.Font = New Font("Times New Roman", 13.0F, FontStyle.Bold)
dgvLinks.ColumnCount = 4
dgvLinks.Columns(0).Width = 60 'ID
dgvLinks.Columns(1).Width = 325 'Site Name 325
dgvLinks.Columns(2).Width = 860 'Site Url 860
dgvLinks.Columns(3).Width = 154 'LastVisit 140
'Option with no blank rows increase col count to 5
'OR increase width of col(3) WHY? because the scroll bar is not showing
' TOTAL Width 1450 Height 488
'=============================
'To Set Col Header Size Mode = Enabled
'To Set Col Header Default Cell Styles DO in Properties
'dgvLinks.Columns(6).DefaultCellStyle.Format = "c"
dgvLinks.ColumnHeadersHeight = 10 'Sans Serif 'Tahoma
dgvLinks.ColumnHeadersDefaultCellStyle.Font = New Font("Sans Serif", 12.0F, FontStyle.Bold)
dgvLinks.ColumnHeadersDefaultCellStyle.ForeColor = Color.Blue
dgvLinks.DefaultCellStyle.BackColor = Color.LightGoldenrodYellow
'DGV Header Names
dgvLinks.Columns(0).Name = "LID"
dgvLinks.Columns(1).Name = "Site Name"
dgvLinks.Columns(2).Name = "Site URL"
dgvLinks.Columns(3).Name = "Last Visit"
dgvLinks.Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(2).SortMode = DataGridViewColumnSortMode.NotSortable
dgvLinks.Columns(3).SortMode = DataGridViewColumnSortMode.NotSortable
End Sub
Any one following this question the FIX that permitted keeping the empty rows was to just omit the sort command in the Update to Database Sub Routine
As far as getting the data from the SQLite DB into the grid… you almost have it in the ViewSearches method. The command text looks good; however you are using an SQLiteDataReader. This is resorting to reading the data line by line.
I suggest you use the SQLiteDataAdapter instead. With it you can get the DataTable from the DB in one shot. First create and initialize a DataSet, then create a new SQLiteDataAdapter then add your command to the data adapter something like…
DataSet ds = new DataSet();
using (SQLiteDataAdapter sqlDA = new SQLiteDataAdapter()) {
conn.Open();
sqlDA.SelectCommand = cmd.CommanText;
sqlDA.Fill(ds, “tableName”);
if (ds.Tables.Count > 0) {
//return ds.Tables[“tableName”];
dgvLinks.DataSource = ds.Tables[“tableName”];
}
}
This will add a DataTable to the DataSet ds called “tableName” if the query succeeded.
Then simply use that DataTable as a DataSource to the grid… something like…
dgvLinks.DataSource = ds.Tables[“tableName”];

add listbox values to access database windows form application

I have a calculator with two textboxes where the user puts a number in each one. They then click a plus, minus, divide, or multiply button and it does that function to the numbers. These numbers are saved to a listbox called listbox1. When the user clicks to display the results, the listbox is populated with all their saved values, and the application is SUPPOSED to save the listbox items to an access database. it is not working. Below is my code, where numFirst is the name of a category in the database table:
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles
btnDisplay.Click
ListBox1.Items.Clear()
For arrayindex As Integer = 0 To intarrayCount - 1
ListBox1.Items.Add(Input(arrayindex))
ListBox1.Text = Convert.ToString(ListBox1.Items.Item(arrayindex))
Next arrayindex
Dim query As String = "SELECT * FROM wk6"
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\helse_000\Desktop\APU\VB Advanced\week4\ENTD461_wk4_Andrew_Helsel\ENTD461_wk2_Andrew_Helsel\calculator.mdb"
Dim command As OleDbCommand = New OleDbCommand
Dim var1 As String = Convert.ToString(ListBox1.Items.Item(0))
command.CommandText = "INSERT into wk6 (numFirst) VALUES (" + var1 + ")"
Figured it out, removed the select all query string and made my textbox fields into parameters after modifying their results a bit to fit the format I needed for the table.
For i As Integer = 0 To ListBox1.Items.Count - 1
Dim firstString As String = Convert.ToString(ListBox1.Items.Item(i))
Dim leftPart As String = firstString.Split(Convert.ToChar
(strButtonSelected))(0)
Dim rightPart As String = firstString.Split(Convert.ToChar("="))(1)
Dim a As Integer = firstString.IndexOf(strButtonSelected)
Dim b As Integer = firstString.IndexOf("=")
Dim secNum = firstString.Substring(a + 1, b - 4)
secNum = secNum.Trim
Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Users\helse_000\Desktop\APU\VB Advanced\week4\ENTD461_wk4_Andrew_Helsel\ENTD461_wk2_Andrew_Helsel\calculator.mdb")
Dim command As OleDbCommand = New OleDbCommand
Dim cmdstring As String = "INSERT INTO wk6 (numFirst, numSecond, Operator, equals, Answer)" + " VALUES (#firstName,#lastName,#Operator,#equals,#answer)"
command = New OleDbCommand(cmdstring, conn)
command.Parameters.AddWithValue("#firstName", leftPart)
command.Parameters.AddWithValue("#lastName", secNum)
command.Parameters.AddWithValue("#Operator", strButtonSelected)
command.Parameters.AddWithValue("#equals", "=")
command.Parameters.AddWithValue("#answer", rightPart)
conn.Open()
command.ExecuteNonQuery()
conn.Close()

how to Flip dataset and display in datagridview

I try to flip dataset to display column as rows by using this code but it does not work :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button.Click
Dim ds2 As New DataSet
Dim dt2 As New DataTable
Dim com1 As String = "select col1,col2,col3 from table1"
ds2 = FlipDataSet(ds2)
Dim dp As New SqlDataAdapter(com1, conn)
dp.Fill(dt2)
DGV_lev1.DataSource = dt2.DefaultView
End Sub
and use this function to flip dataset :
Private Function FlipDataSet(old_DataSet As DataSet) As DataSet
Dim ds As New DataSet()
For Each dt As DataTable In old_DataSet.Tables
Dim table As New DataTable()
For i As Integer = 0 To dt.Rows.Count
table.Columns.Add(Convert.ToString(i))
table.Columns(0).ColumnName = "Fields"
If i = 0 Then
Continue For
Else
table.Columns(i).ColumnName = "Customer " & i
End If
Next
Dim r As DataRow
For k As Integer = 0 To dt.Columns.Count - 1
r = table.NewRow()
r(0) = dt.Columns(k).ToString()
For j As Integer = 1 To dt.Rows.Count
r(j) = dt.Rows(j - 1)(k)
Next
table.Rows.Add(r)
Next
ds.Tables.Add(table)
Next
Return ds
End Function
to make datagirdview display from this :
to this :
can anyone help me
thank you
Try this, it worked in a quick test I did:
Private Function Transpose(ByVal table As DataTable) As DataTable
Dim flippedTable As New DataTable
'creates as many columns as rows in source table
flippedTable.Columns.AddRange(
table.Select.Select(
Function(dr) New DataColumn("col" & table.Rows.IndexOf(dr), GetType(Object))
).ToArray)
'iterates columns in source table
For Each dc As DataColumn In table.Columns
'get array of values of column in each row and add as new row in target table
flippedTable.Rows.Add(table.Select.Select(Function(dr) dr(dc)).ToArray)
Next
Return flippedTable
End Function

Performance improvement on vb.net code

I need to write 50 million records with 72 columns into text file, the file size is growing as 9.7gb .
I need to check each and every column length need to format as according to the length as defined in XML file.
Reading records from oracle one by one and checking the format and writing into text file.
To write 5 crores records it is taking more than 24 hours. how to increase the performance in the below code.
Dim valString As String = Nothing
Dim valName As String = Nothing
Dim valLength As String = Nothing
Dim valDataType As String = Nothing
Dim validationsArray As ArrayList = GetValidations(Directory.GetCurrentDirectory() + "\ReportFormat.xml")
Console.WriteLine("passed xml")
Dim k As Integer = 1
Try
Console.WriteLine(System.DateTime.Now())
Dim selectSql As String = "select * from table where
" record_date >= To_Date('01-01-2014','DD-MM-YYYY') and record_date <= To_Date('31-12-2014','DD-MM-YYYY')"
Dim dataTable As New DataTable
Dim oracleAccess As New OracleConnection(System.Configuration.ConfigurationManager.AppSettings("OracleConnection"))
Dim cmd As New OracleCommand()
cmd.Connection = oracleAccess
cmd.CommandType = CommandType.Text
cmd.CommandText = selectSql
oracleAccess.Open()
Dim Tablecolumns As New DataTable()
Using oracleAccess
Using writer = New StreamWriter(Directory.GetCurrentDirectory() + "\FileName.txt")
Using odr As OracleDataReader = cmd.ExecuteReader()
Dim sbHeaderData As New StringBuilder
For i As Integer = 0 To odr.FieldCount - 1
sbHeaderData.Append(odr.GetName(i))
sbHeaderData.Append("|")
Next
writer.WriteLine(sbHeaderData)
While odr.Read()
Dim sbColumnData As New StringBuilder
Dim values(odr.FieldCount - 1) As Object
Dim fieldCount As Integer = odr.GetValues(values)
For i As Integer = 0 To fieldCount - 1
Dim vals As Array = validationsArray(i).ToString.ToUpper.Split("|")
valName = vals(0).trim
valDataType = vals(1).trim
valLength = vals(2).trim
Select Case valDataType
Case "VARCHAR2"
If values(i).ToString().Length = valLength Then
sbColumnData.Append(values(i).ToString())
'sbColumnData.Append("|")
ElseIf values(i).ToString().Length > valLength Then
sbColumnData.Append(values(i).ToString().Substring(0, valLength))
'sbColumnData.Append("|")
Else
sbColumnData.Append(values(i).ToString().PadRight(valLength))
'sbColumnData.Append("|")
End If
Case "NUMERIC"
valLength = valLength.Substring(0, valLength.IndexOf(","))
If values(i).ToString().Length = valLength Then
sbColumnData.Append(values(i).ToString())
'sbColumnData.Append("|")
Else
sbColumnData.Append(values(i).ToString().PadLeft(valLength, "0"c))
'sbColumnData.Append("|")
End If
'sbColumnData.Append((values(i).ToString()))
End Select
Next
writer.WriteLine(sbColumnData)
k = k + 1
Console.WriteLine(k)
End While
End Using
writer.WriteLine(System.DateTime.Now())
End Using
End Using
Console.WriteLine(System.DateTime.Now())
'Dim Adpt As New OracleDataAdapter(selectSql, oracleAccess)
'Adpt.Fill(dataTable)
Return Tablecolumns
Catch ex As Exception
Console.WriteLine(System.DateTime.Now())
Console.WriteLine("Error: " & ex.Message)
Console.ReadLine()
Return Nothing
End Try

Update old data and add new data using tableadapter in vb.net

My code should update old records and at the same time if the a new record is found it should likewise insert it in the DB... I am using table adpater in doing this method.
Here is the code:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim pta As New PHDSTableAdapters.productdatabaseTableAdapter
pta.Updateproduct(TextBox1.Text, ComboBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text)
pta.Fill(myds.productdatabase)
Dim lta As New PHDSTableAdapters.lotnoTableAdapter
Dim lt = lta.GetDataBylotno(TextBox5.Text)
Dim l As phaccess.PHDS.lotnoRow = lt.Rows(0)
Dim i As Integer
For i = 0 To DGV.Rows.Count - 1
For Each l In myds.lotno
Dim lot As String = DGV.Rows(i).Cells(1).Value
Dim del As Date = DGV.Rows(i).Cells(2).Value
Dim exp As Date = DGV.Rows(i).Cells(3).Value
Dim quantity As Integer = DGV.Rows(i).Cells(4).Value
Dim sup = DGV.Rows(i).Cells(5).Value
Dim disc = DGV.Rows(i).Cells(6).Value
If l.productid = TextBox5.Text Then
Dim lotnumber As String = l.lotnumber
If l.lotnumber <> lot Then
'the error occurs in the insert statement as it would create duplicates 'of the index...the index of the table is the lot number
lta.Insert(TextBox5.Text, lot, del, exp, quantity, sup, disc)
Else
lta.Updateedit(del, exp, quantity, sup, disc, lot)
lta.Fill(myds.lotno)
End If
End If
If lot = "" Then
closeform()
lta.Fill(myds.lotno)
Button3.Enabled = False
Button1.Visible = True
Button3.Visible = False
Button1.Enabled = False
Exit Sub
End If
Next
Next
End Sub
If you need anything else to help me solve this please do ask.
thank you
you can use "DataTable" to upadate DataGridView in your table
For displaying data:
Dim sql As String = "SELECT * FROM table_name"
sCommand = New SqlCommand(sql, conn)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "table_name")
sTable = sDs.Tables("table_name")
DataGridView1.DataSource = sTable
for updating:
sAdapter.Update(sTable)
i hope this helps