Click here to Skip to main content
16,012,168 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using vb.net 2010 (Front end) & Ms Access(2010). I want to Auto generate ID when I click on ADD button. For this I used below mentioned code
C#
cmd.CommandText = "Select Max(SRN) from Employee"
 
 cmd.Connection = con
 
 rd = cmd.ExecuteReader(CommandBehavior.CloseConnection)
 
 If (rd.HasRows) Then
 
 rd.Read()
 
 str = Convert.ToInt32(rd(0))
 
 str = str + 1
 
 txtSRN.Text = str
 
 Else
 
 txtSRN.Text = "1"
 
 End If

system gives me casting error for "str = Convert.ToInt32(rd(0))" statement.
Error:Object cannot be cast from DBNull to other types.

When I use "Convert.ToString(rd(0))" then system throws an error: Conversion from string "" to type 'Double' is not valid. for "str = str + 1" statement
Posted
Updated 27-Nov-13 17:56pm
v2

1 solution

Select Max(SRN) from Employee

This query returns NULL when SRN has no values

Then it satisfies the condition (rd.hasrows) because it has single record as NULL.
When you trying to convert the null value it shows the error Object cannot be cast from DBNull to other typesbecause you cannot convert NULL value into anything .
 
Share this answer
 
Comments
Yogi ,Pune 28-Nov-13 0:30am    
then what should be the code for the same? Please give me.
Tom Marvolo Riddle 28-Nov-13 0:55am    
Try this:
Use ISNULL in sql

Select ISNULL(Max(SRN),0) from Employee

or
cmd.CommandText = "Select Max(SRN) from Employee"

cmd.Connection = con

rd = cmd.ExecuteReader(CommandBehavior.CloseConnection)


rd.Read()

If (rd.HasRows) Then

str = Convert.ToInt32(rd(0))

str = str + 1

txtSRN.Text = str

Else

txtSRN.Text = "1"

End If
Yogi ,Pune 28-Nov-13 1:05am    
Still system throws an error Object cannot be cast from DBNull to other types.
for "str = Convert.ToInt32(rd(0))" statement
Tom Marvolo Riddle 28-Nov-13 1:06am    
and this:
cmd.CommandText = "Select Max(SRN) from Employee"

cmd.Connection = con

rd = cmd.ExecuteReader(CommandBehavior.CloseConnection)

rd.Read()

If (rd.HasRows) Then

If (dr(0) <> DBNull.Value) Then

str = Convert.ToInt32(rd(0))

str = str + 1

txtSRN.Text = str

End If

Else

txtSRN.Text = "1"

End If

I don't know vb.net.i just tried it
Tom Marvolo Riddle 28-Nov-13 1:08am    
Try it and let me know

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900