|
-
Jan 20th, 2010, 10:24 PM
#1
Thread Starter
Member
[RESOLVED] Conversion from type 'DBNull' to type 'String' is not valid
Dear Experts
I use following codes to retrieve data from table, but get error
Conversion from type 'DBNull' to type 'String' is not valid.
Code:
str = "Select * from gpass where vou_no= " & Val(Me.txtGat.Text) & " And Date = '" & Me.txtDat.Text & "'"
dt = GetTable(str)
If (dt.Rows.Count > 0) Then
DataGridView1.Rows.Clear()
For i = 0 To dt.Rows.Count - 1
Me.DataGridView1.Rows.Add()
Me.DataGridView1.Rows(i).Cells(1).Value = IIf(IsDBNull(dt.Rows(i)("tittle")), " ", Trim(dt.Rows(i)("tittle")))
Next
End If
End If
Tittle column of gpass is as
Column------datatype
Tittle--------char(100)
And data in column is as
Null
Null
Null
Please help
-
Jan 20th, 2010, 10:36 PM
#2
Re: Conversion from type 'DBNull' to type 'String' is not valid
In VB 2008 you should be using If, not IIf. One of the problems with IIf is that both possible values get evaluated, so you're trying to Trim a DBNull value even if you don't intend to use it. The new If operator short-circuits, meaning that only the expression for the value that will be returned is evaluated.
That said, why do you need to any of that? Why can't you just do this:
vb.net Code:
Me.DataGridView1.Rows(i).Cells(1).Value = dt.Rows(i)("tittle")
A null value will be displayed in exactly the same way as an empty string in that case, so there's no need to check. If the problem is that you want to Trim a non-empty string then you can do this:
vb.net Code:
Me.DataGridView1.Rows(i).Cells(1).Value = dt.Rows(i)("tittle").ToString().Trim()
By the way, assuming it's English, there's no such word as "tittle". That should probably be "title".
Finally, you should also be using parameters to insert values into your SQL code rather than string concatenation. Follow the Database FAQ link in my signature for more information on that.
-
Jan 21st, 2010, 12:45 PM
#3
Frenzied Member
Re: [RESOLVED] Conversion from type 'DBNull' to type 'String' is not valid
-
Jan 21st, 2010, 05:43 PM
#4
Re: [RESOLVED] Conversion from type 'DBNull' to type 'String' is not valid
 Originally Posted by nbrege
Hmmm... Never say never I guess. Given the context though, I'm going with "title" on this one.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|