Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 随机浏览图像(动画)_Vb.net_Picturebox - Fatal编程技术网

Vb.net 随机浏览图像(动画)

Vb.net 随机浏览图像(动画),vb.net,picturebox,Vb.net,Picturebox,我试图制作一个在文件夹中显示图片的程序。 每个图片的路径都存储在数据库中。 我的问题是它只显示数据库中存储的最后一张图片,而不是所有的图片 代码是: Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.Timer1.Enabled = True End Sub Private Sub Timer1_Tic

我试图制作一个在文件夹中显示图片的程序。 每个图片的路径都存储在数据库中。 我的问题是它只显示数据库中存储的最后一张图片,而不是所有的图片

代码是:

Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.Timer1.Enabled = True

End Sub







Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick




    Try
        Dim ctr As Integer = 0
        Dim pic As String
        Dim sqlconn As New SqlConnection("data source=NMPI_2;initial catalog=IPCS; " & _
                             "password=rhyatco; " & _
                             "persist security info=True; " & _
                             "user id= rhyatco;" & _
                             "packet size=4096")
        sqlconn.Open()
        Dim query As String = "Select picture from Bpicture"
        Dim sqlcomm As New SqlCommand(query, sqlconn)
        Dim reader As SqlDataReader
        reader = sqlcomm.ExecuteReader

        While reader.Read
            pic = reader("picture").ToString
            Me.PictureBox1.Image = Image.FromFile(pic)
            Me.PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
        End While

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

它总是会显示最后一个图像,因为您正在使用While循环检索整个表和所有记录。最后一张图片永远是赢家

有两种可能的解决方案:

从数据库中随机检索一幅图像。检查如何随机选择一行。此解决方案的警告是,每次都要调用数据库


第二,从数据库中检索所有图像,将数据存储在集合中,并从集合中随机选择一个图像。此解决方案的警告是,可能有太多的图像要存储在内存中的集合中,在这种情况下,您必须使用一个图像。

我看到您提供的问题是,每次计时器启动时,您都在运行查询并迭代结果集中的所有行

我认为您真正需要的是在表单加载时下载一次结果集,然后在计时器上切换您正在查看的图片

一种反复循环的方法是下载列表并将其填充到文件名队列中,然后在计时器上执行类似的操作抱歉,我的示例是C:

string fileName = imageFileNameQueue.Dequeue();
PictureBox1.Image = Image.FromFile(fileName);
imageFileNameQueue.Enqueue (fileName); // Put the file back at the back of the queue

对现有解决方案的一个简单改变就是以一定的概率打破while循环。此解决方案的一个问题是,查询结果中后面的图像比前面的图像显示的可能性要小得多

我没有做过任何VB,所以我正在通过Google编码,但您需要在某处创建Random的实例:

Dim rand as new Random()
然后在while循环中,抽取一个随机数,看看是否应该停止:

While reader.Read
    ...
    If rand.Next(10) > 8 Then
       Exit While
    End If
End While
编辑:您还应该将设置图像和SizeMode的代码移出while循环,以便在确定图像后只设置一次