DataGridView Multiple Row Selection Issue - vb.net

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)

Related

Set DataGridViewComboBoxColumn Value Based on a Datatable

I read several article relating to setting the value of a combobox however I still couldn't come up with a solution.
Below is a basic example of what I want to do and in the comments is exactly what I want to do. Any help is appreciated.
Public Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim dt As New DataTable
dt.Columns.Add("ID")
dt.Columns.Add("Name")
dt.Columns.Add("Value")
dt.Columns(0).AutoIncrement = True
For i As Integer = 0 To 20
Dim R As DataRow = dt.NewRow
R("Name") = "Test" & Date.Now & "" & i
If i = 2 Or i = 5 Or i = 6 Or i = 8 Or i = 10 Then
R("Value") = "yes"
Else
R("Value") = "no"
End If
dt.Rows.Add(R)
DataGridView1.DataSource = dt
Next
DataGridView1.ReadOnly = False
Dim cmb As New DataGridViewComboBoxColumn()
cmb.HeaderText = "Select Data"
cmb.Name = "cmb"
cmb.MaxDropDownItems = 2
cmb.Items.Add("True")
cmb.Items.Add("False")
DataGridView1.Columns.Add(cmb)
For Each dr As DataRow In dt.Rows
If dr("Name").ToString = "Test" Then
'set the combo box value to True
Else
'set the combobox value to False
End If
Next
End Sub
You can set the value by setting the Cells.Value...
DataGridView1.Rows(whatrowdoyouwant).Cells("cmb").Value = True
On another note, you set the DataSource to the DataGridView, but loop through the DataTable. If you want to set each row in the DataGridView this wont work.
For Each dr As DataRow In dt.Rows
If dr("Name").ToString = "Test" Then
'set the combo box value to True
Else
'set the combobox value to False
End If
Next
You would need to loop through each DataGridViewRow in the DataGridView and set the ComboBox value. For example...
For i As Integer = 0 To DataGridView1.Rows.Count - 1
If DataGridView1.Rows(i).Cells("Name").Value.ToString = "Test" Then
DataGridView1.Rows(i).Cells("cmb").Value = True
Else
DataGridView1.Rows(i).Cells("cmb").Value = False
End If
Next

Empty lines appears in datagridview

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

Getting Info out of a DataGridView

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

Converting Gridview to DataTable in VB.NET

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

loop data in datalist

How do i loop through each data in the datalist? Because i am currently getting one value from "Label8" which causes my "Label7" to show "No" for all.
Protected Sub DataList2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList2.ItemDataBound
For Each li As DataListItem In DataList2.Items
Dim labelasd As Label = DirectCast(e.Item.FindControl("**Label8**"), Label)
Dim reviewid As Integer = labelasd.Text
Dim connectionString As String = _
ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "Select Count(reviewYes) AS Expr1 From ProductReviewHelp Where ProductReviewID = " & reviewid & ""
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim countofreview As Integer = 0
Dim reviewcountboolean As Boolean
If (reader.Read()) Then
If (IsDBNull(reader.GetValue(0)) = False) Then
countofreview = reader.GetValue(0)
End If
End If
If countofreview = 0 Then
reviewcountboolean = False
Else
reviewcountboolean = True
End If
If (reviewcountboolean = True) Then
Dim label1 As Label = DirectCast(e.Item.FindControl(**"Label7"**), Label)
label1.Text = "Hello"
ElseIf (reviewcountboolean = False) Then
Dim label1 As Label = DirectCast(e.Item.FindControl(**"Label7"**), Label)
label1.Text = "No"
End If
Next
End Sub
How do i loop through each data in the datalist? Because i am currently getting one value from "Label8" which causes my "Label7" to show "No" for all.
You are looping on your DataList2 items but, at every loop, you update the label7 with the logic of the current item, effectively removing the result of the previous loop. This means that, when you reach the last item, the Label7 will reflect the string "Hello" or "No" depending on the logic applied to the last item in your loop.
Apart from this logical error, you have also numerous errors in the code shown.
The connection is never closed.
You use string concatenation instead of parameters.
You use ExecuteReader when in this case an ExecuteScalar is better
suited.
You can iterate through then using a loop here is an example
Try
readFromDL1 = DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
readFromQ = DirectCast(SqlDataSource7.Select(DataSourceSelectArguments.Empty), DataView)
Catch ex As Exception
End Try
'End
'datalist1
i = 0
_rowCount = DataList1.Items.Count
If _rowCount > 0 Then
_getCall = DataList1.Items.Item(i).FindControl("lnkEdit")
End If
For Each readr As DataRowView In readFromQ
findQNumber = readr(1).ToString()
For Each readfdlr1 As DataRowView In readFromDL1
findQNumber1 = readfdlr1(1).ToString
Try
indexofitems = DataList1.Items.Item(i1).ItemIndex
If findQNumber.ToString = findQNumber1.ToString Then
_getCall = DataList1.Items.Item(indexofitems).FindControl("lnkEdit")
_getCall.Text = "Called"
_getCall.Enabled = False
_getCall.ForeColor = Drawing.Color.Red
_getCall.BackColor = Drawing.Color.Yellow
End If
i1 = i1 + 1
Catch e As Exception
End Try
Next
i1 = 0
i = i + 1