When I go to add data in first row there is empty lines that appear below my code, why do these lines appear? I need only to add data in one row and save it.
Dim pringdata As String = "SELECT * FROM itemInfo "
Dim sqlconload As New SqlConnection(sqlcon)
Try
sqlconload.Open()
Dim da As New SqlDataAdapter(pringdata, sqlconload)
ds.Clear()
da.Fill(ds, "itemInfo")
Dim rowcount As Integer
rowcount = ds.Tables("itemInfo").Rows.Count
If rowcount >= 1 Then
DGVorders.Rows.Add(rowcount)
For i = 0 To rowcount - 1
If DGVorders.CurrentRow.Cells(0).Value = ds.Tables("itemInfo").Rows(i).Item("itemCode") Then
DGVorders(1, e.RowIndex).Value = ds.Tables("itemInfo").Rows(i).Item("itemName")
DGVorders(2, e.RowIndex).Value = ds.Tables("itemInfo").Rows(i).Item("Uint1")
DGVorders(4, e.RowIndex).Value = ds.Tables("itemInfo").Rows(i).Item("price1")
End If
Next
End If
sqlconload.Close()
Catch ex As Exception
End Try
End Sub
Modify the "AllowUsersToAddRows" property to remove that blank line.
Example:
DataGridView1.AllowUserToAddRows = False
DGVorders.Rows.Add(rowcount) will add rowcount amount of empty rows to your DataGridView. I don't know why you are doing that, it's not as if you are adding values to the cells in those new rows in your for loop.
updated
If dataGridView1.CurrentRow.Cells(0).Value = ds.Tables("itemInfo").Rows(i)("itemCode") Then
Dim newRow As DataGridViewRow = TryCast(dataGridView1.CurrentRow.Clone(), DataGridViewRow)
newRow.Cells(1).Value = ds.Tables("itemInfo").Rows(i)("itemName")
newRow.Cells(2).Value = ds.Tables("itemInfo").Rows(i)("Uint1")
newRow.Cells(3).Value = ds.Tables("itemInfo").Rows(i)("price1")
dataGridView1.Rows.Add(newRow)
End If
Related
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”];
I'm new to vb.net so I'm seeking for help,
I have method to create buttons in panel layout, and what I want is to set the TEXT for each button from database table ( but the customer TEXT ),
so how can I do it?
this is the method to generate buttons:
Private Sub GenerateTable(columnCount As Integer, rowCount As Integer)
'Clear out the existing controls, we are generating a new table layout
TableLayoutPanel1.Controls.Clear()
'Clear out the existing row and column styles
TableLayoutPanel1.ColumnStyles.Clear()
TableLayoutPanel1.RowStyles.Clear()
'Now we will generate the table, setting up the row and column counts first
TableLayoutPanel1.ColumnCount = columnCount
TableLayoutPanel1.RowCount = rowCount
For x As Integer = 0 To columnCount - 1
'First add a column
TableLayoutPanel1.ColumnStyles.Add(New ColumnStyle(SizeType.AutoSize))
For y As Integer = 0 To rowCount - 1
'Next, add a row. Only do this when once, when creating the first column
If x = 0 Then
TableLayoutPanel1.RowStyles.Add(New RowStyle(SizeType.AutoSize))
End If
'Create the control, in this case we will add a button
Dim cmd As New Button()
cmd.Width = 200
cmd.Height = 40
Dim count As Integer = TableLayoutPanel1.Controls.OfType(Of Button)().ToList().Count
fill_combobox
cmd.Name = "button_" & (count + 1)
cmd.Text = "button_" & (count + 1)
AddHandler cmd.Click, AddressOf Button_Click
Panel1.Controls.Add(cmd)
'cmd.Text = String.Format("({0}, {1})", x, y)
'Finally, add the control to the correct location in the table
TableLayoutPanel1.Controls.Add(cmd, x, y)
Next
Next
End Sub
this is how to call all customers TEXT or id as list of strings from database :
Dim myList As New List(Of String)()
Private Sub fill_combobox()
Try
If SQL.conn.State = ConnectionState.Open Then
SQL.conn.Close()
End If
SQL.conn.Open()
Dim cmd As New SqlCommand()
cmd.Connection = SQL.conn
cmd.CommandText = "SELECT cust_id FROM customers order by date"
Dim dr As SqlDataReader = cmd.ExecuteReader
While dr.Read
Dim esection As String = dr.Item(0)
myList.Add(String.Format(esection))
End While
dr.Close()
SQL.conn.Close()
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
Im elaborating on Subazs' comment. It could be easier to create a collection or List(of Button) then add all of your buttons into this as you itterate them into the flowtable. You can then call back to these at a later date, they will be stored in the list until you dispose of the form. NOTE they are with the form if you code it like this.
I have altered your code slightly too, you must remember to dispose the cmd as well as closing the connection (I had an awful experience not doing this which cost me!)
Dim myList As New List(Of String)
Dim myButtons As List(Of Button)
Public Sub Run_Me()
Retrieve_Customers()
'You can change the 5 and it will change the layout panel for you... :)
GenerateTable_and_Buttons(5)
MsgBox("All done!")
End Sub
'Replaces your (Fill_Combo_Box) method
Private Sub Retrieve_Customers()
Try
myList = New List(Of String)
If Sql.conn.State = ConnectionState.Open Then Sql.conn.Close()
Sql.conn.Open()
'Do you want to add in the customer name instead of ID? - if so we can change here...
Dim qry As String = "SELECT cust_id FROM customers order by date"
Dim cmd As New SqlCommand(qry, Sql.conn)
Dim dr As SqlDataReader = cmd.ExecuteReader
While dr.Read
Dim s As String = dr.Item(0)
myList.Add(String.Format(s))
End While
dr.Close()
cmd.Dispose()
Sql.conn.Close()
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
'Now we have built a list of the customer - myList we can go on to count these...
End Sub
Private Sub GenerateTable_and_Buttons(columnCount As Integer)
If myList Is Nothing Then Exit Sub 'Just exit if we have no customers?
myButtons = New List(Of Button)
'This will round UP to make sure we have enough rows - also can do something like +1 on end if want extra?
Dim rowCount As Integer = CInt(Math.Round(Math.Ceiling(myList.Count / columnCount), 0))
Dim tlp As TableLayoutPanel = Me.TableLayoutPanel1
'Clear out the existing controls, we are generating a new table layout
tlp.Controls.Clear()
'Clear out the existing row and column styles
tlp.ColumnStyles.Clear()
tlp.RowStyles.Clear()
'Now we will generate the table, setting up the row and column counts first
tlp.ColumnCount = columnCount
tlp.RowCount = rowCount
Dim count As Integer = 0
For x As Integer = 0 To columnCount - 1
'First add a column
tlp.ColumnStyles.Add(New ColumnStyle(SizeType.AutoSize))
For y As Integer = 0 To rowCount - 1
'Next, add a row. Only do this when once, when creating the first column
If x = 0 Then
tlp.RowStyles.Add(New RowStyle(SizeType.AutoSize))
End If
'Create the control, in this case we will add a button
Dim cmd As New Button
cmd.Width = 200
cmd.Height = 40
'<<Add the customer ID into the TAG of the control, the tag is great place to store things
'We can then access the tag in another method, ie if we want to open it using your Button_Click
'method. We can say :
'Dim CustID As String = sender.Tag
'Then we can do other things with the ID....>>
If mylist.count > count then
cmd.Tag = myList(count)
cmd.Text = myList(count)
end if
'fill_combobox() ' I dont know why this is here?
cmd.Name = "button_" & (count + 1)
cmd.Text = "button_" & (count + 1)
AddHandler cmd.Click, AddressOf Button_Click
myButtons.Add(cmd)
'<<<<<<<<<<<<<<<<<
Panel1.Controls.Add(cmd) '<<<<<<<<< Whats Panel1????
'>>>>>>>>>>>>>>>>>>
'Finally, add the control to the correct location in the table
tlp.Controls.Add(cmd, x, y)
count += 1
Next
Next
End Sub
I need to get the information that is in each cell located in the datagrid view of the rows that the user selects. I have the selecting rows down, I just need help with getting the information in the cell. Right now it just returns as DataGridVewRow { Index=7} when the data is really a string. Here is my function
Private Function getCoordinates()
Dim dt As New DataTable
Dim dt2 As New DataTable
'Dim r As DataRow
Dim n As Integer = 0
Dim selectedItems As DataGridViewSelectedRowCollection = dgv.SelectedRows
dt = dgv.DataSource
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect
dgv.MultiSelect = True
Dim i = dgv.CurrentRow.Index
dt2.Columns.Add("Position")
Try
If selectedItems Is Nothing Then
For n = 0 To dt.Rows.Count - 1
dt2.Rows.Add(n)
dt2.Rows(n)("Position") = dt.Rows.Item(n)("Mouse Position")
Next
Else
For Each selectedItem As DataGridViewRow In selectedItems
dt2.Rows.Add(selectedItem)
dt2.Rows(selectedItem.Index)("Position") = dt.Rows.Item(selectedItem.Index)("Mouse Position")
Next
End If
Catch ex As Exception
MsgBox("Error", MsgBoxStyle.Exclamation, "Error!")
End Try
Return dt2
End Function
You get the text of the cells via the DataGridViewRow's Cells property. The following example would get the text from the first cell in each selected row:
Dim strContents As String = String.Empty
For Each selectedItem As DataGridViewRow In selectedItems
strContents += " First Cell's Text: " & selectedItem.Cells(0).Text
Next
I am using this function to create datatable from gridviews. It works fine with Gridviews with AutoGenerateColumns = False and have boundfields or template fileds. But if I use it with Gridviews with AutoGenerateColumn = True I only get back an empty DataTable. Seems Gridview viewstate has been lost or something. Gridview is binded on PageLoad with If Not IsPostback. I can't think of anything else to make it work. Hope someone can help me.
Thanks,
Public Shared Function GridviewToDataTable(gv As GridView) As DataTable
Dim dt As New DataTable
For Each col As DataControlField In gv.Columns
dt.Columns.Add(col.HeaderText)
Next
For Each row As GridViewRow In gv.Rows
Dim nrow As DataRow = dt.NewRow
Dim z As Integer = 0
For Each col As DataControlField In gv.Columns
nrow(z) = row.Cells(z).Text.Replace(" ", "")
z += 1
Next
dt.Rows.Add(nrow)
Next
Return dt
End Function
Slight modification to your function above. If the autogenerate delete, edit or select button flags are set, the values for the fields are offset by one. The following code accounts for that:
Public Shared Function GridviewToDataTable(ByVal PassedGridView As GridView, ByRef Error_Message As String) As DataTable
'-----------------------------------------------
'Dim Tbl_StackSheets = New Data.DataTable
'Tbl_StackSheets = ReportsCommonClass.GridviewToDataTable(StackSheetsGridView)
'-----------------------------------------------
Dim dt As New DataTable
Dim ColInd As Integer = 0
Dim ValOffset As Integer
Try
For Each col As DataControlField In PassedGridView.Columns
dt.Columns.Add(col.HeaderText)
Next
If (PassedGridView.AutoGenerateDeleteButton Or PassedGridView.AutoGenerateEditButton Or PassedGridView.AutoGenerateSelectButton) Then
ValOffset = 1
Else
ValOffset = 0
End If
For Each row As GridViewRow In PassedGridView.Rows
Dim NewDataRow As DataRow = dt.NewRow
ColInd = 0
For Each col As DataControlField In PassedGridView.Columns
NewDataRow(ColInd) = row.Cells(ColInd + ValOffset).Text.Replace(" ", "")
ColInd += 1
Next
dt.Rows.Add(NewDataRow)
Next
Error_Message = Nothing
Catch ex As Exception
Error_Message = "GridviewToDataTable: " & ex.Message
End Try
Return dt
End Function
I am trying to check for multiple selections in a DataGridView with a For... Next Loop, but even though I have selected multiple rows, the only row with the property Selected=True is the first row in the selection. Is there a way around this?
MultiSelect is true on the DataGridView.
My code is as follows:
For Each dr As DataGridViewRow In dgv.Rows
If dr.Selected = True Then
intSelectedRow = dr.Index
SetTime("KeyEntry", dgv.Name, intSelectedRow)
End If
Next
Thanks
Try this:
Dim selectedItems As DataGridViewSelectedRowCollection = dgv.SelectedRows
For Each selectedItem As DataGridViewRow In selectedItems
'Add code to handle whatever you want for each row
Next
End Sub
Dim Message As String = String.Empty
Dim FNL As FinalRpt = New FinalRpt()
For Each ItemRow As DataGridViewRow In DGVItems.Rows
Dim ISSelected As Boolean = Convert.ToBoolean(ItemRow.Cells("MyChkBox").Value)
If ISSelected Then
Message &= Environment.NewLine
Message &= ItemRow.Cells("I_ID").Value.ToString()
Dim SelectedRow As Integer = DGVItems.Rows.GetRowCount(DataGridViewElementStates.Selected)
Dim RPTItemsDA As OleDbDataAdapter
Dim RPTItemsDS As DataSet
Dim I As Integer
For I = 0 To SelectedRow Step 1
RPTItemsDA = New OleDbDataAdapter("Select Distinct * From stkrpt Where I_ID = " & DGVItems.SelectedRows(I).Index.ToString() & "", DBConnect)
RPTItemsDS = New DataSet
RPTItemsDA.Fill(RPTItemsDS, "stkrpt")
FNL.DGVReport.DataSource = RPTItemsDS
FNL.DGVReport.DataMember = "stkrpt"
Next
FNL.MdiParent = MDIParent1
FNL.StartPosition = FormStartPosition.CenterScreen
FNL.WindowState = FormWindowState.Maximized
Me.Hide()
FNL.Show()
ISSelected = False
End If
Next
MessageBox.Show(Message)