Problem retrieving data: System.IndexOutOfRangeException: There is no row at position 0 - sql-server

Dim command As New SqlCommand("SELECT * From tblUserInfo WHERE Username='" & Trim(frmdashboard.ToolStripLabel4.Text) & "'", con)
Dim table As New DataTable()
Dim sqlAdapter As New SqlDataAdapter(command)
sqlAdapter.Fill(table)
Me.UserTypeTextBox.Text = table.Rows(0)(10).ToString()
Me.UsernameTextBox.Text = table.Rows(0)(9).ToString()
Me.Email_AddressTextBox.Text = table.Rows(0)(12).ToString()
Me.PositionTextBox.Text = table.Rows(0)(1).ToString()
Me.NameTextBox.Text = table.Rows(0)(2).ToString()
Me.AddressTextBox.Text = table.Rows(0)(3).ToString()
Me.Date_of_BirthDateTimePicker.Value = table.Rows(0)(4).ToString()
Me.AgeTextBox.Text = table.Rows(0)(5).ToString()
Me.SexComboBox.Text = table.Rows(0)(6).ToString()
Me.Telephone_NumberTextBox.Text = table.Rows(0)(7).ToString()
Me.Mobile_NumberTextBox.Text = table.Rows(0)(8).ToString()
Me.Security_Question_1TextBox.Text = table.Rows(0)(13).ToString()
Me.Security_Question_2TextBox.Text = table.Rows(0)(15).ToString()
Dim img() As Byte
img = table.Rows(0)(17)
Dim ms As New MemoryStream(img)
Me.PicturePictureBox.Image = Image.FromStream(ms)
This should retrieve the data of a specific person. The error I get is
System.IndexOutOfRangeException: There is no row at position 0

You are assuming that your query will return at least one record which might/might not be true all times. You should first check if your tables has at least one row as below:
if ( table.Rows != null && tables.Rows.Count > 0)
{
Dim img() As Byte;
img = table.Rows(0)(17)
Dim ms As New MemoryStream(img)
Me.PicturePictureBox.Image = Image.FromStream(ms)
}

Related

Why image cannot be saved in database

I'm using VB.NET and SQL Server for my system. I have a problem saving an image into the database. I need to save and retrieve image on the same page but I get an error:
unable to cast System.DBNull to system bytes.
I have tried several coding to fix my coding but it does not worked.
Code for retrieve image.
Dim id As String = txtImages.Text.Trim() 'txtImages is textbox name
Image1.Visible = id <> ""
If id <> "" Then
Dim dt As DataTable = GetData((Convert.ToString("SELECT ImagePic FROM masterlist WHERE id
='") & Request.QueryString("id")) + "'") 'image data will be select depend on what user search in the
serch textbox
If dt.Rows.Count > 0 Then
Dim bytes As Byte() = TryCast(dt.Rows(0)("ImagePic"), Byte())
Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Image1.ImageUrl = Convert.ToString("data:images/png;base64,") & base64String
Else
Image1.ImageUrl = ""
Image1.AlternateText = "No image present in database with the name" 'if there is no image
in db the message will displayed
End If
End If
End Sub
Code for save image
Dim fileName As String = String.Empty
Dim filePath As String = String.Empty
Dim getPath As String = String.Empty
Dim pathToStore As String = String.Empty
Dim bytes As [Byte]()
Dim fs As FileStreamenter code here
Dim br As BinaryReader
Dim cmd As New SqlCommand("Updateonlyimage_Sp3", cs) ' SQL command for this page is inside SQL Server I declare it as Insertapprovalcustom_Sp2"
cmd.CommandType = CommandType.StoredProcedure
Try
If FileUpload1.HasFile Then
fileName = FileUpload1.FileName
filePath = Server.MapPath("HSCODE/" & Convert.ToString(System.Guid.NewGuid()) & fileName)
'path to doucument inside approval_pdf file
FileUpload1.SaveAs(filePath)
cmd.Parameters.AddWithValue("#id", Request.QueryString("id"))
cmd.Parameters.AddWithValue("#ImagePicName", fileName)
Dim getPos As Integer = filePath.LastIndexOf("\")
Dim len As Integer = filePath.Length()
getPath = filePath.Substring(getPos, len - getPos)
pathToStore = getPath.Remove(0, 1)
cmd.Parameters.AddWithValue("#ImagePicPath", pathToStore)
fs = New FileStream(filePath, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
bytes = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
cmd.Parameters.AddWithValue("#ImagePic", bytes)
cmd.Parameters.AddWithValue("#ContentType", FileUpload1.PostedFile.ContentType)

how to populate array of controls (labels) using database vb.net

I am doing my homework but stuck on a part. Problem is, How can i populate seat number in array of controls(labels) using database. I already created labels and a class to retrieve all rows from database but how can i apply it in main form and populate labels.
--------------------------Class---------------------------------------
Public Shared Function getOneRow(PK As Integer) As datMovieTimes
Dim returnRow As New datMovieTimes(0)
Dim connDB As New SqlConnection
connDB.ConnectionString = Conn.getConnectionString
Dim command As New SqlCommand
command.Connection = connDB
command.CommandType = CommandType.Text
command.CommandText = SQLStatements.SELECT_1_BY_ID
command.Parameters.AddWithValue("#Key", PK)
Try
connDB.Open()
Dim dR As IDataReader = command.ExecuteReader
If dR.Read() Then
returnRow.showingID = PK
If Not IsDBNull(dR(Fields.movieID)) Then returnRow.movieID = dR(Fields.movieID)
If Not IsDBNull(dR(Fields.dateTime)) Then returnRow.dateTime = dR(Fields.dateTime)
If Not IsDBNull(dR(Fields.isActive)) Then returnRow.isActive = dR(Fields.isActive)
End If
Catch ex As Exception
Console.WriteLine(Err.Description)
End Try
Return returnRow
End Function
Public Shared Function getAllRows() As Generic.List(Of datMovieTimes)
Dim returnRows As New Generic.List(Of datMovieTimes)
Dim connDB As New SqlConnection
connDB.ConnectionString = Conn.getConnectionString
Dim command As New SqlCommand
command.Connection = connDB
command.CommandType = CommandType.Text
command.CommandText = SQLStatements.SELECT_ALL
Try
connDB.Open()
Dim dR As IDataReader = command.ExecuteReader
Do While dR.Read()
Dim Row As New datMovieTimes(0)
If Not IsDBNull(dR(Fields.showingID)) Then Row.showingID = dR(Fields.showingID)
If Not IsDBNull(dR(Fields.movieID)) Then Row.movieID = dR(Fields.movieID)
If Not IsDBNull(dR(Fields.dateTime)) Then Row.dateTime = dR(Fields.dateTime)
If Not IsDBNull(dR(Fields.isActive)) Then Row.isActive = dR(Fields.isActive)
returnRows.Add(Row)
Loop
Catch ex As Exception
Console.WriteLine(Err.Description)
End Try
Return returnRows
End Function
-----------------------------main form-----------------------------------------
Public Sub createSeat()
Dim S1 As Label
For X As Integer = 1 To _MAX_X
For Y As Integer = 1 To _MAX_Y
S1 = New Label
S1.Height = 25
S1.Width = 25
S1.BackColor = Color.LightGreen
S1.Top = 100 + (X - 1) * (S1.Height + 5)
S1.Left = 200 + (Y - 1) * (S1.Width + 5)
S1.TextAlign = ContentAlignment.MiddleCenter
S1.Text = Y.ToString
AddHandler S1.Click, AddressOf GenericLabel_Click
Me.Controls.Add(S1)
_SeatArray(X, Y) = S1
Next
Next
For X As Integer = 0 To 9
_AlphaLabel(X) = New Label
_AlphaLabel(X).Height = 25
_AlphaLabel(X).Width = 25
_AlphaLabel(X).BackColor = Color.Transparent
_AlphaLabel(X).Top = 130 + (X - 1) * (_AlphaLabel(X).Height + 6)
_AlphaLabel(X).Left = 170
_AlphaLabel(X).Text = _AlphaName(X)
Me.Controls.Add(_AlphaLabel(X))
Next
End Sub
Private Sub GenericLabel_Click(sender As Object, e As EventArgs)
Dim L As New Label
L = DirectCast(sender, Label)
If L.BackColor = Color.LightGreen Then
L.BackColor = Color.Orange
clickLess -= 1
ElseIf L.BackColor = Color.Orange Then
L.BackColor = Color.LightGreen
clickLess += 1
End If
clickCount += 1
Me.lblRemainingCount.Text = clickLess.ToString
Me.nudTicketsCount.Value = clickCount
If clickLess <= 0 Then
MsgBox("No more seats left.", MsgBoxStyle.OkOnly, "House Full")
End If
End Sub
Database pic
When creating labels, insert one more line:
S1.Name = "MyLabel" & X & Y
When accessing the label:
Dim MyCurrentLabel as Label
MyCurrentLabel = CType("MyLabel" & X & Y, Label)
Then you can do things with the current label:
MyCurrentLabel.Text = "Hello World"
current image
Now it is something like this, so it want to change the colour to red if it is paid according to database.
Thanks
I found the answer, sorry i forgot to mention it because i was busy in completing the project
----------------------Seat creation----------------------------------------
Public Sub createSeat()
Dim S1 As Label
Dim numValue As Integer = 1
For X As Integer = 1 To _MAX_X
For Y As Integer = 1 To _MAX_Y
S1 = New Label
S1.Height = 25
S1.Width = 25
S1.BackColor = Color.LightGreen
S1.Top = 180 + (X - 1) * (S1.Height + 5)
S1.Left = 200 + (Y - 1) * (S1.Width + 5)
S1.TextAlign = ContentAlignment.MiddleCenter
S1.Text = Y.ToString
' S1.Text = numValue
S1.Name = "Label" & numValue
AddHandler S1.Click, AddressOf GenericLabel_Click
Me.Controls.Add(S1)
_SeatArray(X, Y) = S1
numValue += 1
Next
Next
For X As Integer = 0 To 9
_AlphaLabel(X) = New Label
_AlphaLabel(X).Height = 25
_AlphaLabel(X).Width = 25
_AlphaLabel(X).BackColor = Color.Transparent
_AlphaLabel(X).Top = 210 + (X - 1) * (_AlphaLabel(X).Height + 6)
_AlphaLabel(X).Left = 170
_AlphaLabel(X).Text = _AlphaName(X)
Me.Controls.Add(_AlphaLabel(X))
Next
End Sub
-------------------------------populate seat number----------------------------------
Public Sub populateSeatNumber()
Dim connectionString As String = DBL.Conn.getConnectionString
Dim connection As New SqlConnection(connectionString)
connection.Open()
Dim selectStatement As String = "SELECT * FROM datTicketsSold"
Dim selectCommand As New SqlCommand(selectStatement, connection)
Dim daSoldTickets As New SqlDataAdapter(selectCommand)
Dim dsSoldTickets As DataSet = New DataSet
daSoldTickets.Fill(dsSoldTickets, "datTicketsSold")
connection.Close()
Dim dtTickets As DataTable = dsSoldTickets.Tables("datTicketsSold")
Dim row As DataRow
For Each row In dtTickets.Rows
If row(3) = True Then
CType(Controls("Label" & row(2)), Label).BackColor = Color.Red
redCounter += 1
Else
CType(Controls("Label" & row(2)), Label).BackColor = Color.Yellow
yellowCounter += 1
End If
Next
Me.lblReservedCount.Text = yellowCounter.ToString
Me.lblSoldCount.Text = redCounter.ToString
End Sub
Thanks everyone

Converted my code from C# to VB.NET and now it's throwing an error of var

I am converted that code from c# but its give an error var is not define
can you please give me a suggestion what to do , I am new in vb.net. what can i use instead of var
If searchCriteria = "Title" Then
Dim Searchresults As New List(Of SearchResultsTitle)()
Dim searchfields As String() = New String() {"title", ""}
Dim queryparser = New QueryParser(Lucene.Net.Util.Version.LUCENE_29, "title", analyzer)
Dim indexSearcher As New IndexSearcher(directory)
Dim hits = indexSearcher.Search(QueryMaker(searchString, searchfields))
Dim dt As New DataTable()
Dim SrNo As Integer = 1
For i As Integer = 0 To hits.Length() - 1
Dim result As New SearchResultsTitle()
result.SrNo = SrNo
result.Title = hits.Doc(i).GetField("title").StringValue()
result.Accessionno = hits.Doc(i).GetField("AccessionNo").StringValue()
result.Author = hits.Doc(i).GetField("Author").StringValue()
result.Location = hits.Doc(i).GetField("location").StringValue()
result.ClassNo = hits.Doc(i).GetField("ClassNo").StringValue()
result.Status = hits.Doc(i).GetField("status").StringValue()
Searchresults.Add(result)
SrNo = SrNo + 1
Next
Dim outputText As New StringBuilder()
Dim query = queryparser.Parse(txtSearch.Text)
Dim result = searcher.Search(query)
'now facets
Dim facetsText As New StringBuilder()
For Each result As<b> Var</b> In GetFacets(query, "title").Where(Function(k) k.Value > 0).OrderByDescending(Function(k) k.Value)
facetsText.AppendLine(item.Key + " ( " + item.Value + " )")
Next
Dim doc As New FlowDocument()
' Add paragraphs to the FlowDocument.
doc.Blocks.Add(New Paragraph(New Run(outputText.ToString())))
doc.Blocks.Add(New Paragraph(New Run("title")))
doc.Blocks.Add(New Paragraph(New Run(facetsText.ToString())))
rtbResult.Document = doc
dGridResults.ItemsSource = Searchresults
End If
For Each is defined as:
For Each o As Type In Collection
'do something with o
Next
Your Var in For Each is not definded. Var has to be an existing objecttype. Try KeyValuePair(of, ) (return type of GetFacets(..)) or something similar instead. Deleting As Var is also an option.

Background Worker and ODBC Query

I want to run the fetching of a Database into a background worker but it seems to be crashing without Visual Studio returning me an error in my code.
Here's the code in the DoWork:
Private Sub ITSM_Fetch_BW_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles ITSM_Fetch_BW.DoWork
Dim sql As String = "xxxx"
Dim ConnString As String = "DRIVER={AR System ODBC Driver};ARServer=xxxx;ARServerPort=xxxx;ARPrivateRpcSocket=xxxx;UID=xxxx;PWD=xxxx;ARAuthentication=;ARUseUnderscores=1;SERVER=NotTheServer"
Dim connection As New Odbc.OdbcConnection(ConnString)
connection.Open()
Dim ODBC_Command As New Odbc.OdbcCommand(sql, connection)
Dim ODBC_reader As Odbc.OdbcDataReader
'Load the Data into the local Memory
ODBC_reader = ODBC_Command.ExecuteReader
e.Result = ODBC_reader
ODBC_reader.Close()
End Sub
Private Sub ITSM_Fetch_BW_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles ITSM_Fetch_BW.RunWorkerCompleted
Data = New DataTable
Data.Load(e.Result)
Dim Count_ToDo(5) As String
Count_ToDo(0) = "Product_Name"
Count_ToDo(1) = "Status"
Count_ToDo(2) = "Language"
Count_ToDo(3) = "Assigned_Group"
Count_ToDo(4) = "Priority"
Count_ToDo(5) = "Company"
For Each Item As String In Count_ToDo
Dim i As Integer = 0
Dim ITEM_Count(0, 1) As String
For Each Ticket As DataRow In Data.Rows
'PART FOR THE CI
If IsDBNull(Ticket.Item(Item)) = False Then
Dim IsInIndex As Integer = -1
If i = 0 Then
ITEM_Count(0, 0) = Ticket.Item(Item)
ITEM_Count(0, 1) = 1
Else
For x As Integer = 0 To ITEM_Count.GetLength(0) - 1
If ITEM_Count(x, 0) = Ticket.Item(Item) Then
IsInIndex = x
End If
Next
If IsInIndex = -1 Then
Dim ITEM_Count_Temp(ITEM_Count.GetLength(0), ITEM_Count.GetLength(0)) As String
ITEM_Count_Temp = ITEM_Count
ReDim ITEM_Count(ITEM_Count.GetLength(0), 1)
For x As Integer = 0 To ITEM_Count_Temp.GetLength(0) - 1
For y As Integer = 0 To ITEM_Count_Temp.GetLength(1) - 1
ITEM_Count(x, y) = ITEM_Count_Temp(x, y)
Next
Next
ITEM_Count(ITEM_Count.GetLength(0) - 1, 0) = Ticket.Item(Item)
ITEM_Count(ITEM_Count.GetLength(0) - 1, 1) = 1
Else
ITEM_Count(IsInIndex, 1) = ITEM_Count(IsInIndex, 1) + 1
End If
End If
Else
'IF NULL
End If
i = i + 1
Next
'CI_COUNT FILLING
'ORDERING BY COUNT
Dim ITEM_obj = New List(Of obj)
Dim ITEM_ToObj As String = ""
Dim ITEMCount_ToObj As String = ""
For x As Integer = 0 To ITEM_Count.GetLength(0) - 1
ITEM_ToObj = ITEM_Count(x, 0)
ITEMCount_ToObj = ITEM_Count(x, 1)
ITEM_obj.Add(New obj(ITEM_ToObj, ITEMCount_ToObj))
Next
ITEM_obj = OrderItem(ITEM_obj)
Dim Item_Count_listview As ListViewItem
For Each Itemobj As obj In ITEM_obj
Dim Transfer_Array(2) As String
Transfer_Array(0) = Itemobj.Item
Transfer_Array(1) = Itemobj.Item_Count
Item_Count_listview = New ListViewItem(Transfer_Array)
Select Case Item
Case "Product_Name"
CI_Count_Table.Items.Add(Item_Count_listview)
Case "Status"
Status_Count_Table.Items.Add(Item_Count_listview)
Case "Language"
Language_Count_Table.Items.Add(Item_Count_listview)
Case "Assigned_Group"
AssignedGroup_Count_Table.Items.Add(Item_Count_listview)
Case "Priority"
Priority_Count_Table.Items.Add(Item_Count_listview)
Case "Company"
LOB_Count_Table.Items.Add(Item_Count_listview)
Case Else
MsgBox("No Category Of this type exist. Programming Issue. Item is: " & Item)
End Select
Next
Next
End Sub
What is not possible to run into a background worker like this?
regards,

Import CSV into DataGrid

In winForms adding a CSV to a DataGrid was quite easy. I am now trying to add this to a Silverlight DataGrid. Here is my attempt - which yields 3 columns Capacity|Count|Items - mind you the values are correct 83|83|_ on each row. There are 83 rows, but the columns should be 23 with diff values in each. Thanks for looking and enjoy your bounty!
Code:
Try
Dim ofd As New OpenFileDialog
If ofd.ShowDialog Then
If IO.File.Exists(ofd.File.FullName) Then
Dim srsCol As New List(Of List(Of String))
Using fs As IO.FileStream = ofd.File.OpenRead
Using sr As New IO.StreamReader(fs)
While Not sr.Peek = -1
srsCol.Add(New List(Of String)(sr.ReadLine.Split(","c).ToList))
End While
End Using
End Using
dgStaff.ItemsSource = srsCol
End If
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
I decided to use the BindableDataGrid from CodePlex Since the binding is being set dynamically I had to come up with a Random string generator and assign that for the binding and all is well.
csvDs.Tables.Clear()
Try
Dim ofd As New OpenFileDialog
If ofd.ShowDialog Then
If IO.File.Exists(ofd.File.FullName) Then
csvDs.Tables.Add(csvDt)
Using fs As IO.FileStream = ofd.File.OpenRead
Using sr As New IO.StreamReader(fs)
Dim i As Integer
While Not sr.EndOfStream
If i = 0 Then
Dim cols = sr.ReadLine.Split(","c)
For ii As Integer = 0 To cols.Count - 1
Dim rndValue As String = RndColName()
Dim col As New BindableDataGrid.Data.DataColumn(rndValue)
rndValues.Add(rndValue)
col.DataType = GetType(System.String)
col.Caption = ii.ToString
col.ReadOnly = True
col.AllowReorder = False
col.AllowResize = False
col.AllowSort = False
csvDt.Columns.Add(col)
AddItemsToCb(ii)
Next
Dim row As New BindableDataGrid.Data.DataRow
For _i As Integer = 0 To cols.Count - 1
Dim s As String = cols(_i).Replace("""", String.Empty)
row(rndValues(_i)) = s
csvValues.Add(s)
Next
csvDt.Rows.Add(row)
Else
Dim cols = sr.ReadLine.Split(","c)
Dim row As New BindableDataGrid.Data.DataRow
For _i As Integer = 0 To cols.Count - 1
row(rndValues(_i)) = cols(_i).Replace("""", String.Empty)
Next
csvDt.Rows.Add(row)
End If
i += 1
End While
End Using
End Using
dgStaff.DataSource = csvDs
dgStaff.DataMember = "csvTable"
dgStaff.DataBind()

Resources