Unusual Glitch when Opening Forms - vb.net

When I maximise a form in my project and open another form from it (using a button), I'm getting an unusual glitch which I can only explain with the use of the screenshots below.
In this image, I have got an order screen and a freight screen. The order screen is maximised into an MDI screen when I hit the 'Add Freight' button, then upon opening the freight management screen, it is setting both forms to WindowState.Normal, which I'm doing programmatically and I understand why it sets both forms to normal window state, however, as you can, it is leaving a trace of the order screen behind in maximised view.
To explain more clearly, the forms have been changed from WindowState.Maximized to WindowState.Normal, and in the image the form in the top left corner is fine, but the order form is still showing in both normalised and maximised, but the maximised window doesn't exist, it disappears when you move the other screens around.
The strangest thing about this is that I'm using the same code to open other windows in the exact same way elsewhere in the program yet this glitch isn't happening.
There are only 2 "parent" forms which do this when opening other forms from within them.
Has anyone else ever had this issue? What is a way around it? This also happens even if I open the other form in maximised mode, so it's not as simple as just opening it in maximised view.
The code to open the form in the example is the following:
ugProducts.UpdateData()
Try
Dim dt As New DataTable
dt = ugProducts.DataSource
Dim ordnum As Integer
Dim osql As New OleDbCommand
osql.CommandType = CommandType.Text
osql.Connection = con
osql.CommandText = "SELECT [Order_Number] FROM [Order_Freight] WHERE [Order_Reference] = ?"
osql.Parameters.AddWithValue("#onum", lblReference.Text.ToString)
ordnum = Convert.ToInt32(osql.ExecuteScalar)
Dim ORef As String
ORef = lblReference.Text
Dim FNumber As Integer
Dim fsql As New OleDbCommand
fsql.CommandType = CommandType.Text
fsql.Connection = con
fsql.CommandText = "SELECT [Freight_Number] FROM [Order_Freight] WHERE [Order_Reference] = ?"
fsql.Parameters.AddWithValue("#fnum", lblReference.Text.ToString)
FNumber = Convert.ToInt32(fsql.ExecuteScalar)
Dim PC As String
Try
PC = ugProducts.ActiveRow.Cells("Product_Code").Text.ToString
Catch
PC = ugProducts.Rows(0).Cells("Product_Code").Text.ToString
End Try
Dim SC As String
Try
SC = ugProducts.ActiveRow.Cells("Supplier_Code").Text.ToString
Catch
SC = ugProducts.Rows(0).Cells("Supplier_Code").Text.ToString
End Try
Dim f As New frmEditFreight(con, dt, Me, cmbCustCode.Text, ordnum, ORef, FNumber, PC, SC)
f.MdiParent = Me.MdiParent
f.Show()
Catch ex As Exception
errorLog(ex)
End Try
Then, on the form that is loaded, I have this
Me.Location = New Point(0, 0)
Me.WindowState = FormWindowState.Normal
txtTotal.ReadOnly = True
lftable = New DataTable
If isNewOrder = False Then
Try
For Each dc As DataColumn In lineTable.Columns
If dc.ColumnName = "Order_Number" OrElse dc.ColumnName = "Product_Code" OrElse dc.ColumnName = "Supplier_Code" Then
lftable.Columns.Add(New DataColumn(dc.ColumnName, dc.DataType))
End If
Next
Dim product As String = ""
Dim supplier As String = fOrder.cmbSupplier.Text
Dim ds As New DataSet
Dim da As New OleDbDataAdapter("SELECT * FROM [Order_Freight] WHERE [Order_Number] = ?", con)
da.SelectCommand.Parameters.Add("#num", OleDbType.Integer).Value = orderNum
da.Fill(ds)
Dim nDt As New DataTable
nDt = ds.Tables(0).Copy()
For Each row As DataRow In nDt.Rows
product = row.Item("Product_Code")
For Each dr As DataRow In lineTable.Rows
If dr.RowState <> DataRowState.Deleted Then
If dr.Item("Product_Code") = product Then
dr.Delete()
Else
End If
Else
If dr.Item("Product_Code", DataRowVersion.Original) = product Then
dr.Delete()
Else
End If
End If
Next
Next
For Each dr As DataRow In lineTable.Rows
If dr.RowState <> DataRowState.Deleted Then
dr.Item("Order_Number") = orderNum
End If
Next
Me.ugProducts.DataSource = lineTable
For Each dc As UltraGridColumn In ugProducts.DisplayLayout.Bands(0).Columns
Dim cName As String = dc.ToString
Select Case cName
Case "Product_Code"
dc.Hidden = False
Case "Order_Number"
dc.Hidden = False
Case "Supplier_Code"
dc.Hidden = False
Case Else
dc.Hidden = True
End Select
Next
loadAddresses(custCode, con)
dtEstDelivery.Value = Date.Today
ugProducts.DisplayLayout.Bands(0).Override.CellClickAction = CellClickAction.RowSelect
selectedTable.Columns.Add("Product_Code")
selectedTable.Columns.Add("Supplier_Code")
selectedTable.Columns.Add("RowIndex")
freightTable = New DataTable
With freightTable.Columns
.Add("Freight_Number")
.Add("Address_Code")
.Add("Est_Delivery")
.Add("Product_Code")
.Add("Freight_Desc")
.Add("Freight_Val", GetType(Decimal))
.Add("Supplier_Code")
.Add("freeDelivery", GetType(Boolean))
End With
ugFreight.DataSource = freightTable
ugSelected.DataSource = selectedTable
ugSelected.DisplayLayout.Bands(0).Override.CellClickAction = CellClickAction.RowSelect
Catch ex As Exception
errorLog(ex)
End Try
Else
Try
Me.ugProducts.DataSource = lineTable
For Each dc As UltraGridColumn In ugProducts.DisplayLayout.Bands(0).Columns
Dim cName As String = dc.ToString
Select Case cName
Case "Product_Code"
dc.Hidden = False
Case "Product_Description"
dc.Hidden = False
dc.Header.Caption = "Description"
Case "Supplier_Code"
dc.Hidden = False
dc.Header.Caption = "Supplier"
Case Else
dc.Hidden = True
End Select
Next
loadAddresses(custCode, con)
dtEstDelivery.Value = Date.Today
ugProducts.DisplayLayout.Bands(0).Override.CellClickAction = CellClickAction.RowSelect
selectedTable.Columns.Add("Product_Code")
selectedTable.Columns.Add("Supplier_Code")
selectedTable.Columns.Add("RowIndex")
freightTable = New DataTable
With freightTable.Columns
.Add("Freight_Number")
.Add("Address_Code")
.Add("Est_Delivery")
.Add("Product_Code")
.Add("Freight_Desc")
.Add("Freight_Val", GetType(Decimal))
.Add("Supplier_Code")
.Add("freeDelivery", GetType(Boolean))
End With
ugFreight.DataSource = freightTable
ugSelected.DataSource = selectedTable
ugSelected.DisplayLayout.Bands(0).Override.CellClickAction = CellClickAction.RowSelect
Catch ex As Exception
errorLog(ex)
End Try
End If
bLoading = False
Followed by some ordinary stuff, setting DataTables, loading in data, etc.
The other form which is having the issue has this code:
Try
Dim grid As UltraGrid = DirectCast(sender, UltraGrid)
Dim lastElement As UIElement = ugRates.DisplayLayout.UIElement.LastElementEntered
Dim rowElement As RowUIElement
If TypeOf lastElement Is RowUIElement Then
rowElement = DirectCast(lastElement, RowUIElement)
Else
rowElement = DirectCast(lastElement.GetAncestor(GetType(RowUIElement)), RowUIElement)
End If
If rowElement Is Nothing Then Return
Dim row As UltraGridRow = DirectCast(rowElement.GetContext(GetType(UltraGridRow)), UltraGridRow)
If (row Is Nothing) Then Return
Dim MousePosition As Point = grid.PointToClient(Control.MousePosition)
If Not lastElement.AdjustableElementFromPoint(MousePosition) Is Nothing Then Return
Select Case row.Cells("cType").Value
Case "Acquisition Rate"
Dim supplier As String
If rbtnAllSuppliers.Checked = True Then
supplier = row.Cells("Supp_Code").Value
Else
supplier = cmbSupplier.Text
End If
Dim f As New frmCommission(con, row.Cells("Comm_Code").Value, supplier, True)
f.MdiParent = Me.MdiParent
f.Show()
With the rest of the select case below. The form being opened in this case then has the code
Me.Location = New Point(0, 0)
Me.WindowState = FormWindowState.Normal
Me.Cursor = Cursors.Default
isUpdate = False
Me.ugComm.ContextMenuStrip = cmCommRate
With updateDT.Columns
.Add("Apply", GetType(Boolean)).DefaultValue = False
.Add("Product_Code")
.Add("Commission_Rate")
.Add("Multiplier")
End With
btnCustomerSearch.Enabled = False
Try
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
sql = "SELECT * FROM [System Settings]"
da = New OleDb.OleDbDataAdapter(sql, con)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows(0).Item("enableAqDate") = False Then
rbtnAcq.Enabled = False
End If
If cCode <> "" And sCode <> "" Then
cmbSupp.Text = sCode
cmbSupp_ValueChanged(sender, New EventArgs)
End If
disableControls()
cmbSupp.Refresh()
txtCommCode.Refresh()
ugComm.Refresh()
cmbSupp.Enabled = False
isLoad = False
If isEnquiry = True Then
txtCommCode.Text = cCode
loadEnquiry()
ugComm.Enabled = True
cmdAddRange.Enabled = False
cmdUpdateRange.Enabled = True
cmbSupp.Value = sCode
txtCommCode.Text = cCode
End If
Catch ex As Exception
errorLog(ex)
End Try
When trying to insert the code suggested for making dpiaware = True, I've not been able to see anywhere in the code that this would go?

The culprit seems to be setting the WindowState property to Normal inside the Load event of a mdi child form when active mdi child form is maximized.
At this time the target form is in some intermediate state - the event is called as part of the window handle creation, the handle is already created, Visible property is True (but the form is not really shown on screen), WindowState returns Maximized and trying to set it to Normal leads internally to ShowWindow API call.
It's hard to tell where exactly is the bug (there are a lot of internal flags and windows messages handling inside the Form class), but the end effect is that the MDIClient and the currently active mdi child form are not correctly invalidated, hence the visual effect you are experiencing.
With that being said, there are several workarounds:
(1) At the form being shown side:
Move the Me.WindowState = FormWindowState.Normal to the Shown event.
(2) At the caller side:
(A) Add Me.WindowState = FormWindowState.Normal before f.Show()
or
(B) Add Me.MdiParent.Invalidate(True) after f.Show()
or
(C) Add Me.MdiParent.Refresh() after f.Show()
My personal preference would be the option (1) since it encapsulates a logic which is specific to the called form inside that form.

Related

Search data from FlowLayoutPanel

How can I make my textbox.text when I enter something to fetch results in flowlayoutpanel and if i remove text form textbox to show all again.
Simply search option inside the flowpanel to show found records.
The code that create the flowlayoutpanel when form loads:
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()))
Dim ms As New MemoryStream(CType(row("UserPictureFrom"), Byte()))
Dim ms2 As New MemoryStream(CType(row("UserPictureTo"), Byte()))
listItems(i).Width = FlowLayoutPanel1.Width - 30
listItems(i).Icon = New Bitmap(ms)
listItems(i).Icon2 = New Bitmap(ms2)
listItems(i).OrderFrom = row("orderfrom").ToString()
listItems(i).OrderTitle = row("UserPositionFrom").ToString()
listItems(i).OrderReceiver = row("orderreceiver").ToString()
listItems(i).OrderTitle2 = row("UserPositionTo").ToString()
'listItems(i).ButtonBackground = orderButtonBackString
listItems(i).ButtonText = row("orderstatus").ToString()
listItems(i).OrderDate = row("orderdate")
listItems(i).IDOrder = row("orderid").ToString()
listItems(i).Subject = row("ordersubject").ToString()
listItems(i).SubjectText = row("ordersubjecttext").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
The class:
Public Function ReadItemsTable() As DataTable
Using cons As New SQLiteConnection(ServerStatus)
Using cmd As New SQLiteCommand()
cmd.Connection = cons
'cmd.CommandText = "SELECT * FROM OrdersAssigned ORDER BY ID ASC"
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;"
cons.Open()
Using sda As New SQLiteDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
and on my button "btnSearchOrders_TextChanged" I need to input the search method any ideas how to do that without calling new query?
On the textbox TextChanged event try something like:
For Each myControl As Control In myflowlayoutcontrol.Controls
If myControl.text=mytextboxname.text then
'found it!
End if
'more code goes here
Next
the code inside the .TextChanged function will run every time the text of the textbox change and will search for the text on it in the flow control objects .text strings.
Let me know if you need more help.

Create Previous, Next Buttons in FlowLayoutPanel

can someone help me to add buttons for Previous Next and pages between them.
For example in my FlowLayoutPanel1 it display 4 results, because i do not want to use autoscroll=true
what i want to do is after the 4th results by pressing button to continue to next records display in the flowlayoutpanel and so one.
What i mean is to create outside the flowlayout buttons Previous,1,2,3,4,Next buttons that when click to do action inside the flowlayoutpanel
Demo Buttons
Something like that i would like to create
Here is my code for add stuff in the layoutpanel
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
listItems(i).Icon = orderPicFromString
listItems(i).Icon2 = orderPicFromString2
listItems(i).OrderFrom = row("orderacc").ToString()
listItems(i).OrderTitle = row("orderfrom").ToString()
listItems(i).OrderReceiver = row("orderreceiveracc").ToString()
listItems(i).OrderTitle2 = row("orderreceiver").ToString()
'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
And the code that calls the read of database MS Access DB is like this:
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
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

Image.FromStream is not a member of System.Windows.Forms.DataGridViewImageColumn

So I use this code to display my data in a DataGridView:
Sub display_Infodata()
DGUSERS.Rows.Clear()
Dim sql As New MySqlDataAdapter("select * from tbl_info", con)
Dim ds As New DataSet
DGUSERS.AllowUserToAddRows = False
DGUSERS.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DGUSERS.RowTemplate.Height = 40
sql.Fill(ds, 0)
For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim xx As Integer = DGUSERS.Rows.Add
Dim uid As String = ds.Tables(0).Rows(i).Item(0).ToString
Dim sqls As New MySqlDataAdapter("select * from tbl_other where userid='" & uid & "'", con)
Dim dss As New DataSet
sqls.Fill(dss, 0)
With DGUSERS.Rows(xx)
If dss.Tables(0).Rows.Count > 0 Then
.Cells(0).Value = uid
.Cells(1).Value = ds.Tables(0).Rows(i).Item(2).ToString
.Cells(2).Value = ds.Tables(0).Rows(i).Item(3).ToString
.Cells(3).Value = ds.Tables(0).Rows(i).Item(4).ToString
.Cells(4).Value = ds.Tables(0).Rows(i).Item(5).ToString
.Cells(5).Value = ds.Tables(0).Rows(i).Item(6).ToString
.Cells(6).Value = dss.Tables(0).Rows(0).Item(1).ToString
.Cells(7).Value = ds.Tables(0).Rows(0).Item(2).ToString
.Cells(8).Value = ds.Tables(0).Rows(0).Item(8).ToString
.Cells(9).Value = ds.Tables(0).Rows(0).Item("Image")
.Cells(10).Value = dss.Tables(0).Rows(0).Item(2).ToString
.Cells(11).Value = dss.Tables(0).Rows(0).Item(3).ToString
Else
End If
End With
Next
End Sub
It displays and works, but my problem is that when I try to display the data in the DataGridView of another form it shows the following error:
This is what I use:
Try
With View_Info
Dim index As Integer
Dim selectedRow As DataGridViewRow
selectedRow = DGUSERS.Rows(index)
.UserID.Text = DGUSERS.SelectedRows(0).Cells("UserID").Value
.UserType.Text = DGUSERS.SelectedRows(0).Cells("UserType").Value
.Fname.Text = DGUSERS.SelectedRows(0).Cells("Firstname").Value
.Mname.Text = DGUSERS.SelectedRows(0).Cells("Middlename").Value
.Lname.Text = DGUSERS.SelectedRows(0).Cells("Lastname").Value
.Contact.Text = DGUSERS.SelectedRows(0).Cells("Contact").Value
.Standing.Text = DGUSERS.SelectedRows(0).Cells("Standing").Value
.Guardian.Text = DGUSERS.SelectedRows(0).Cells("Guardian").Value
.ContactG.Text = DGUSERS.SelectedRows(0).Cells("GuardianContact").Value
.DPCreated.Text = DGUSERS.SelectedRows(0).Cells("DateCreated").Value
.DPValidity.Text = DGUSERS.SelectedRows(0).Cells("Validity").Value
Dim img As Byte()
img = DGUSERS.SelectedRows(0).Cells("Image").Value
Dim ms As New MemoryStream(img)
.UploadImage.Image = Image.FromStream(ms)
.Show()
.Focus()
End With
Catch ex As Exception
MsgBox(ex.Message & " Please select a corresponding records.", MsgBoxStyle.Exclamation)
End Try
Any help please?
It's hard to see the full picture, but the problem is most likely that you have created a DataGridViewImageColumn which you've chosen to call Image.
The compiler will always choose local variables, properties or classes over library/pre-imported namespace objects with the same name. Thus, your column by the name Image will be used rather than System.Drawing.Image because the former is "more local".
Try specifying the namespace as well and it should work:
.UploadImage.Image = System.Drawing.Image.FromStream(ms)
So what I did to solve this is by:
Dim pCell As New DataGridViewImageCell
pCell = Me.DGUSERS.Item("Picture", e.RowIndex)
.UploadImage.Image = byteArrayToImage(pCell.Value)
and using this function:
Private Function byteArrayToImage(ByVal byt As Byte()) As Image
Dim ms As New System.IO.MemoryStream()
Dim drwimg As Image = Nothing
Try
ms.Write(byt, 0, byt.Length)
drwimg = New Bitmap(ms)
Finally
ms.Close()
End Try
Return drwimg
End Function

Buttons Added to FlowLayoutPanel pile up on top of each other

I'm using VS 2012 (vb.net) and I have a form with a flowLayoutPanel which is meant to contain an unknown number of buttons. To make it simple, basically, when the form Loads I fetch items from a table based one some criteria and then a use a For...Next block to add a button for each item to the flowLayoutPanel. So if I find 5 items I add 5 buttons all named differently but the problem is that they seem to pile up on each other instead of lining up nicely. When I use a button to add the items one after the other it works fine but when I use the For...Next block it does not work. I have tried refreshing the flowLayoutPanel after adding each button, I have tried to set the location of each new button relative to the location of the previous button but it still does to work.
I have researched this for over a week now and there is a ton of stuff out there but nothing specifically deals with this.
Thanks for your help.
This is the relevant part of my code:
`Try
If conn.State <> ConnectionState.Open Then
conn.Open()
End If
sql = "SELECT ItemCode, Description, NormalPrice FROM items WHERE items.Class = 'ICE CREAM'"
cmd = New MySqlCommand(sql, conn)
da.SelectCommand = cmd
'fill dataset
da.Fill(ds, "items")
rowscount = ds.Tables("items").Rows.Count
If rowscount > 0 Then 'there are records so go ahead
Dim ID As Integer
Dim desc As String
Dim newbutton As New Button
Dim newCode As New TextBox
For i As Integer = 0 To rowscount - 1
ID = ds.Tables("items").Rows(i).Item("ItemCode")
desc = ds.Tables("items").Rows(i).Item("Description")
newCode.Name = "mnuCode" & i
newCode.Text = ID
newCode.Visible = False
Me.Controls.Add(newCode)
newbutton.Name = "mnuButton" & i
newbutton.Text = desc
newbutton.Size = New Size(150, 100)
newbutton.BackColor = Color.Orange
newbutton.ForeColor = Color.White
newbutton.Font = New Font("Arial", 16, FontStyle.Bold)
newbutton.TextAlign = ContentAlignment.MiddleCenter
newbutton.Text = Regex.Unescape(desc)
newbutton.Top = (150 + (i * 100))
fPanel.Refresh()
AddHandler newbutton.Click, AddressOf ButtonClicked
fPanel.Controls.Add(newbutton)
Next
End If
ds.Reset()
conn.Close()
Catch ex As MySqlException
Finally
conn.Dispose()
End Try`
You are not creating multiple buttons. You just keep changing the properties on the same button over and over again. Since Button is a reference type, you need to call New each time you need a new object instance
For instance, instead of this:
Dim newbutton As New Button
For i As Integer = 0 To rowscount - 1
' ...
fPanel.Controls.Add(newbutton)
Next
Do this:
For i As Integer = 0 To rowscount - 1
Dim newbutton As New Button
' ...
fPanel.Controls.Add(newbutton)
Next
Or:
Dim newbutton As Button = Nothing
For i As Integer = 0 To rowscount - 1
newbutton = New Button
' ...
fPanel.Controls.Add(newbutton)
Next

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