Click column header - vb.net

I want to order the items in listview by the time or payment or name I'm use now the combobox but i want to do it from the listview header when i clicked on header column i want the listview sorted by it , i'm use this code with the combo box please help me.
Private Sub OrderBy()
Try
Dim OB As String
If ComboBox1.Text = "ID" Then
OB = "ID"
ElseIf ComboBox1.Text = "Name" Then
OB = "StudentName"
ElseIf ComboBox1.Text = "Payment" Then
OB = "Payment"
ElseIf ComboBox1.Text = "Time" Then
OB = "LessonTime"
ElseIf ComboBox1.Text = "Date" Then
OB = "LessonDate"
End If
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter("select * from Tend order by " & OB & "", con)
da.Fill(dt)
Dim myrow As DataRow
For Each myrow In dt.Rows
ListView1.Items.Add(myrow.Item(0))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(1))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(2))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(3))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(4))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(5))
Next

Explaining better, use the ColumnClick event and use e.Column to know the index of column that was clicked
EDIT: This isn't the best way to do it, but it is the easiest way for you now.
Private Sub OrderBy(Col as Integer)
Try
Dim OB As String
Select Case Col
'Depending on the order of columns in your table
Case 0
OB = "ID"
Case 1
OB = "StudentName"
Case 2
OB = "Payment"
Case 3
OB = "LessonTime"
Case 4
OB = "LessonDate"
End Select
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter("select * from Tend order by " & OB & "", con)
da.Fill(dt)
ListView1.Items.Clear
For Each myrow As DataRow In dt.Rows
Dim item = ListView1.Items.Add(myrow.Item(0))
item.SubItems.Add(myrow.Item(1))
item.SubItems.Add(myrow.Item(2))
item.SubItems.Add(myrow.Item(3))
item.SubItems.Add(myrow.Item(4))
item.SubItems.Add(myrow.Item(5))
Next
End Try
End Sub
Private Sub ColumnClick(ByVal o As Object, ByVal e As ColumnClickEventArgs) Handles ListView1.ColumnClick
OrderBy(e.Column)
End Sub

I experienced the same problem, I found a Microsoft tutorial in c# and converted to VB.NET a while back.
You can check out my converted open source project on: http://www.sourcecodester.com/visual-basic-net/5415/how-sort-listview-control-column-header-vbnet.html
It shows how to add new items, separated into columns, and you are able to sort the list view, by clicking on the column header. You can also set the default sort method.

Related

Exception when adding a new row from the RowLeave event

I have an unbound datagridview, set the option to allow user to add row to True, and all I want is that once I "complete" a row, the datagridview automatically should create a new empty row, so I set the method
DataGridView1.Rows.Add()
in the DataGridView1_Leave event, but once the row is finished and exception comes out:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll - Unable to complete this operation in this event handler
What does it mean? It should be plain simple code, but I don't know how to solve
Here is the situation:
That's the recipient DataGridView. When I'm on the first blank row (which is created by the AllowUserToAddRow = true) and I press F3 a modal form is opened with another DataGridView containing products to select
and here's the code for the KeyDown event in the recipient DataGridView
Private Sub DataGridView1_KeyDown(sender As Object, e As KeyEventArgs) Handles DataGridView1.KeyDown
If e.KeyCode = Keys.F3 Then
If frmZoomArticoli.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim codart As String = frmZoomArticoli.DataGridView1.CurrentCell.Value.ToString()
RicercaxCodiceArticolo(codart)
End If
End If
End Sub
Here the sub RicercaxCodiceArticolo(codart) which fills the recipient DataGridView with the selected product:
Private Sub RicercaxCodiceArticolo(ByVal codiceart As String)
Dim strsql As String
Dim cmd As SqlCommand
Dim source As New BindingSource
'Dichiariamo le variabili che ospitano i dati di riga
Dim codice As String
Dim descrizione As String
Dim unitamisura As String
Dim quantita As Double = 1.0
Dim codiceiva As Double
Dim costobase As Double
Dim prezzobase As Double
Dim costoultimo As Double
Dim giacenza As Double
Dim sconto1 As Double
Dim sconto2 As Double
connection.Open()
strsql = "SELECT CODICEARTICOLO AS 'Codice', DESCRIZIONEARTICOLO AS 'Descrizione', UNITAMISURA AS 'Um', CODICEIVA AS 'Iva' " _
& ", COSTOBASE AS 'Costo', PREZZOBASE AS 'Prezzo', SCONTO1 As 'Sc1', SCONTO2 As 'Sc2', COSTOULTIMO AS 'CostoUlt' " _
& ", BARCODE AS 'Barcode', NOTEARTICOLO AS 'Note' ,CATEGORIAARTICOLO AS 'Categ.Art.', GIACENZA AS 'Giacenza' " _
& ", FORNITOREPREF AS 'Fornit. Pref.' FROM Articoli " _
& " WHERE CODICEARTICOLO = '" & codiceart & "'"
cmd = New SqlCommand()
cmd.CommandText = strsql
cmd.CommandType = CommandType.Text
cmd.Connection = connection
source.DataSource = cmd.ExecuteReader()
'Assegniamo i dati letti nel bindingsource alle variabili
codice = source.Current!Codice
descrizione = source.Current!Descrizione
unitamisura = source.Current!Um
codiceiva = Convert.ToDouble(source.Current!Iva)
costobase = Convert.ToDouble(source.Current!Costo)
prezzobase = Convert.ToDouble(source.Current!Prezzo)
costoultimo = Convert.ToDouble(source.Current!Costoult)
giacenza = Convert.ToDouble(source.Current!Giacenza)
sconto1 = Convert.ToDouble(source.Current!Sc1)
sconto2 = Convert.ToDouble(source.Current!Sc2)
'Riempiamo le celle con i dati estratti dal BindingSource
With DataGridView1.CurrentRow
.Cells("grdCodice").Value = codice
.Cells("grdDescrizione").Value = descrizione
.Cells("grdUM").Value = source.Current!Um
.Cells("grdQuantita").Value = quantita
If TipoMovimento = "Carico" Then
.Cells("grdPrezzoUnitario").Value = source.Current!CostoUlt
Else
.Cells("grdPrezzoUnitario").Value = source.Current!Prezzo
End If
.Cells("grdSconto1").Value = sconto1
.Cells("grdSconto2").Value = sconto2
.Cells("grdSconto3").Value = 0.0
.Cells("grdSconto4").Value = 0.0
'Per calcolare il prezzo totale di riga dobbiamo tenere presente le
'informazioni che abbiamo gia' in anagrafica, ovvero il costo/prezzo
'e gli sconti
'Blocco di controllo sul tipo movimento
If TipoMovimento = "Carico" Then
If sconto1 > 0 Then
.Cells("grdPrezzoTotale").Value = quantita * (costoultimo * (costoultimo * sconto1 / 100))
Else
.Cells("grdPrezzoTotale").Value = quantita * costoultimo
End If
ElseIf TipoMovimento = "Scarico" Then
If sconto1 > 0 Then
.Cells("grdPrezzoTotale").Value = quantita * (prezzobase * (prezzobase * sconto1 / 100))
Else
.Cells("grdPrezzoTotale").Value = quantita * prezzobase
End If
End If
.Cells("grdAliquotaIva").Value = codiceiva
End With
connection.Close()
End Sub
and that's the result in the recipient DataGridView:
now, suppose that I don't want to edit the selected row because I don't need to edit quantity, or price, or whatever, but I just want to insert a new row to keep inserting other products. When I tab until the end of the row I want to create a new row, and that's why I wrote the DataGridView1.Rows.Add() in the RowLeave event of the DataGridView, but that's where the exception occurs:
I'm sorry for all the descriptions are in italian, but if you need any other details feel free to ask.
If there's nothing I can do all that remains is to add a button outside the DataGridView which adds a new row from there. Any other solution is welcomed.
Is there some reason you do not use a DataSource for the grid? Then you could simply add the row to the DataSource.
If you insist on manually adding the rows, then the problem you currently have is that the code is never “adding” a new row to the grid. The code simply uses the grids CurrentRow to set the values. This may work but the grids “new” row will not get created.
It is questionable to use the grids CurrentRow in this manner... So instead of using the grids CurrentRow for this, I suggest you “add” a new row in the RicercaxCodiceArticolo method. Something like below should add the new row and the “new-new” empty row should be at the bottom…
Dim newRowIndex As Int32
newRowIndex = DataGridView1.Rows.Add()
With DataGridView1.Rows(newRowIndex)
.Cells("grdCodice").Value = codice
.Cells("grdDescrizione").Value = descrizione
'.....
End With

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”];

Trying to add a list of suppliers in an array and then i am adding it to listbox and combobox using `.addrange` but i am receiving error

I retrieved list of suppliers from database and saved it in an array TOTAL_SUPPLIERS_ARRAY NOW i am trying it to add in the listbox or combobox but it shows an error on runtime saying "VALUE CAN NOT BE NULL" but if i try to add it with an loop it works properly why is it not working with .addrange ?
Sub GET_SUPPLIERS_DETAILS()
Dim CON As New MySqlConnection("server=localhost; username=root; password=Masoom1; database=airtech_db;")
Dim cmd As New MySqlCommand("Select * from `Suppliers`;", CON)
Dim da As New MySqlDataAdapter("Select * from `Suppliers`;", CON)
Dim ds As New DataSet
Dim dr As MySqlDataReader
Dim TOTAL_SUPPLIERS As Integer
CON.Open()
da.Fill(ds)
dr = cmd.ExecuteReader
TOTAL_SUPPLIERS = ds.Tables(0).Rows.Count
Dim TOTAL_SUPPLIERS_ARRAY(TOTAL_SUPPLIERS) As String, ARRAYINDEX As Integer
Do While dr.Read() = True
TOTAL_SUPPLIERS_ARRAY(ARRAYINDEX) = dr("Supplier_Name").ToString()
ARRAYINDEX += 1
Loop
CON.Close()
Dim cbCell As New DataGridViewComboBoxCell
For k = 0 To DataGridView1.Rows.Count - 1
cbCell = DataGridView1.Rows(k).Cells("Supplier_Name")
For iIndex = 0 To UBound(TOTAL_SUPPLIERS_ARRAY) - 1
cbCell.Items.Add(TOTAL_SUPPLIERS_ARRAY(iIndex))
Next
Next
ListBox1.Items.AddRange(TOTAL_SUPPLIERS_ARRAY)
ComboBox1.Items.AddRange(TOTAL_SUPPLIERS_ARRAY)
For I As Integer = 0 To UBound(TOTAL_SUPPLIERS_ARRAY) - 1
TextBox1.Text += TOTAL_SUPPLIERS_ARRAY(I) & " - "
Next I
End Sub
This part works only as i added it through a loop
For I As Integer = 0 To UBound(TOTAL_SUPPLIERS_ARRAY) - 1
TextBox1.Text += TOTAL_SUPPLIERS_ARRAY(I) & " - "
Next I
listbox.addrange command and combobox.addrange command not working
Here you have an issue TOTAL_SUPPLIERS_ARRAY(TOTAL_SUPPLIERS). Array declared in VB - array(upper-bound). Upper bound is 1 less than count. So, you should do TOTAL_SUPPLIERS_ARRAY(TOTAL_SUPPLIERS - 1).
But why struggle? Just use list
Dim myList as New List(of String)
While dr.Read()
myList.Add(dr("Supplier_Name").ToString())
Loop
And then, if you still need array, you can use LINQ - myList.ToArray
ListBox1.DataSource = myList.ToArray()

Checking if datagridview already exist in another datagridview before inserting using checkbox

i have two datagridview and i am trying to insert value in datagridview1 to datagridview2 using checkbox on button click.
For i As Integer = DataGridView1.Rows.Count - 1 To 0 Step -1
Dim c As Boolean
c = DataGridView1.Rows(i).Cells(0).Value
If c = True Then
With DataGridView1.Rows(i)
DataGridView2.Rows.Insert(0, .Cells(0).Value, .Cells(1).Value, .Cells(2).Value, .Cells(3).Value, .Cells(4).Value, .Cells(5).Value)
End With
End If
Next
My code will insert the data everytime i insert it. I want to prevent inserting the same data on datagridview2. As you can see the in the image below everytime i tried to insert the same checkbox i can add it multiple times.
Thank you so much.
This is how i populate my datagridview1.
Sub dgv1_SubjectList()
query = "SELECT subject_id AS '#', subject_name AS 'Descriptive Title', subject_units AS 'Units', sem AS 'Semester', year_level AS 'Year Level' " & _
" FROM subject WHERE course = '" & cmb_Course.Text & "' AND CURRICULUM = '" & curriculum & "' "
da = New MySqlDataAdapter(query, myconn)
da.Fill(ds, "subject")
DataGridView1.DataSource = ds.Tables(0)
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
On datagridview2 i add empty column directly in datagridview2.
Thank you. Sorry for late update.
I tried my best to reproduce your environment.
DataGridView1.AllowUserToAddRows = True
DataGridView2.AllowUserToAddRows = True
DataGridView1.Rows.Insert(DataGridView1.Rows.Count - 1, True, "Row1Col1", "Row1Col2", "Row1Col3", "Row1Col4", "Row1Col5", "Row1Col6")
DataGridView1.Rows.Insert(DataGridView1.Rows.Count - 1, True, "Row2Col1", "Row2Col2", "Row2Col3", "Row2Col4", "Row2Col5", "Row2Col6")
DataGridView2.Rows.Insert(DataGridView2.Rows.Count - 1, False, "Row1Col1", "Row1Col2", "Row1Col3", "Row1Col4", "Row1Col5", "Row1Col6")
For i As Integer = DataGridView1.Rows.Count - 2 To 0 Step -1
If DataGridView1.Rows(i).Cells(0).Value Then
Dim AlreadyInGrid As Boolean = False
Dim ColumnsCount As Integer = DataGridView1.Columns.GetColumnCount(DataGridViewElementStates.Displayed)
For j As Integer = DataGridView1.Rows.Count - 2 To 0 Step -1
For k As Integer = 1 To ColumnsCount - 1
If DataGridView1.Rows(i).Cells(k).Value <> DataGridView2.Rows(j).Cells(k).Value Then Exit For
AlreadyInGrid = (k = ColumnsCount - 1)
Next
If AlreadyInGrid Then Exit For
Next
If Not AlreadyInGrid Then
With DataGridView1.Rows(i)
DataGridView2.Rows.Insert(DataGridView2.Rows.Count - 1, False, .Cells(1).Value, .Cells(2).Value, .Cells(3).Value, .Cells(4).Value, .Cells(5).Value, .Cells(6).Value)
End With
End If
End If
Next
To me it looks like you want to move the row, if that is the case you need not worry about checking if it already exists because it would not be available to try and add it again.
Public Class Form1
Dim ds As New DataSet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Begin sample setup
ds.Tables.Add(New DataTable With {.TableName = "Table1"})
With ds.Tables(0)
.Columns.Add("Select", GetType(Boolean))
.Columns.Add("ID", GetType(Integer))
.Columns.Add("Column2", GetType(String))
.Rows.Add(False, 1, "test1")
.Rows.Add(False, 2, "test2")
.Rows.Add(False, 3, "test3")
.Rows.Add(False, 4, "test4")
End With
Dim dt As DataTable = ds.Tables(0).Clone
dt.TableName = "Table2"
ds.Tables.Add(dt)
DataGridView1.DataSource = ds.Tables(0)
DataGridView2.DataSource = ds.Tables(1)
'end sample setup
End Sub
Private Sub ButtonAddToDT2_Click(sender As Object, e As EventArgs) Handles ButtonAddToDT2.Click
Validate()
Dim SelRows() As DataRow = ds.Tables(0).Select("Select=True")
For Each DtRow As DataRow In SelRows
ds.Tables(1).ImportRow(DtRow)
ds.Tables(0).Rows.Remove(DtRow)
Next
End Sub
End Class
If it is not your intention to remove the row and you really do want to see if the row exists in datagridview2 let me know and we can make some minor modifications to this code.

Delete Row / Remove Row

I want to delete my rows in gridview, but when I try many code the error are same.
When I try this
Using sqlCon As New SqlConnection(PyrDLL.Koneksi.ConnectionString)
Using cmd As New SqlCommand()
cmd.CommandText = "xyz"
cmd.Connection = sqlCon
sqlCon.Open()
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
Gridview1.DataSource = dt
Gridview1.DataBind()
sqlCon.Close()
If Gridview1.Rows.Count = 0 Then
Dim dtempty As DataTable = Nothing
dtempty = (DirectCast(Gridview1.DataSource, DataTable)).Clone()
dtempty.Rows.Add(dtempty.NewRow())
Gridview1.DataSource = dtempty
Gridview1.DataBind()
Gridview1.Rows(0).Visible = False
'Gridview1.Rows(0).Controls.Clear()
Else
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("rupiah") = PyrDLL.Decrypt(dt.Rows(i)("rupiah"))
dt.Rows(i)("rupiah") = Decimal.Parse(dt.Rows(i)("rupiah")).ToString()
'i = i + 1
Next
Gridview1.DataBind()
For i As Integer = Gridview1.Rows.Count - 1 To 1 Step -1
Dim row As GridViewRow = Gridview1.Rows(i)
Dim prevrow As GridViewRow = Gridview1.Rows(i - 1)
If (TryCast(Gridview1.Rows(i).Cells(1).FindControl("lblketerangan"), Label).Text.ToString() = TryCast(Gridview1.Rows(i - 1).Cells(1).FindControl("lblketerangan"), Label).Text.ToString()) And (TryCast(Gridview1.Rows(i).Cells(0).FindControl("lblcomp"), Label).Text.ToString() = TryCast(Gridview1.Rows(i - 1).Cells(0).FindControl("lblcomp"), Label).Text.ToString()) Then
Dim total As Integer = Convert.ToDecimal(TryCast(Gridview1.Rows(i - 1).Cells(2).FindControl("lblrupiah"), Label).Text)
Dim total2 As Integer = Convert.ToDecimal(TryCast(Gridview1.Rows(i).Cells(2).FindControl("lblrupiah"), Label).Text)
Dim total3 As Decimal
total3 = total + total2
DirectCast(Gridview1.Rows(i - 1).Cells(2).FindControl("lblrupiah"), Label).Text = Decimal.Parse(total3).ToString()
row.Visible = False
'Gridview1.Rows.Remove(Gridview1.Rows(i)) <--- if i comment here its run without problem
End If
Next
End If
End Using
End Using
the error
Remove' is not a member of 'System.Web.UI.WebControls.GridViewRowCollection'
Can you help me?
now, i hide the row after i sum it but i want to auto delete / remove row after i sum it not only hide
Thanks
I am not sure what you are trying to do when there are no rows, the gridview would be empty
You should do the following instead:
'Call GetData() every time you want to bind data to the gridview
Private Function GetData()
Gridview1.DataSource = Nothing
Gridview1.DataBind()
Dim strQuery = "SELECT..."
Dim dt As New DataTable()
Using sqlCon As New SqlConnection(PyrDLL.Koneksi.ConnectionString)
Using cmd As New SqlCommand(strQuery, sqlCon)
'Add cmd parameters as required to prevent SqlInjection
sqlCon.Open()
Using ada As New SqlDataAdapter(cmd)
ada.Fill(dt)
Gridview1.DataSource = dt
Gridview1.DataBind()
End Using
End Using
End Using
End Function
When handling the data in the gridview you can use RowDataBound, you could then call a separate function to handle deleting a row after your logic is handled where the criteria is met to delete a row
Protected Sub Gridview1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles Gridview1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'Handle databound logic
End If
End Sub
You should be able to tailor this to your needs, just called GetData() everytime you need to rebind data to the gridview
I solved my problem
i cant remove rows from data gridview but i remove data from data table and bind it after thats
thanks everyone