Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,
I am trying to insert mobile number into a variable which is of type int (in sqlserver's database table) from Asp.Net's Textbox control and I am getting this exception

System.Data.SqlClient.SqlException: Error converting data type nvarchar to int.

my code is as follows....
in .aspx file
XML
<asp:TableRow>
                        <asp:TableCell>Mobile No</asp:TableCell><asp:TableCell>:</asp:TableCell><asp:TableCell>
                            <asp:TextBox ID="txtMob" runat="server" TextMode="Phone" /></asp:TableCell>
                    </asp:TableRow>


in .aspx.cs file
SqlParameter p13 = new SqlParameter("Mobile",txtMob.Text.Trim());
cmd.Parameters.Add(p14);
int rowAffected = cmd.ExecuteNonQuery();

when I am trying in the above way i am getting "Error converting data type nvarchar to int." Exception

and when I'm trying to convert data type to int i.e.,
SqlParameter p13 = new SqlParameter("Mobile",Convert.ToInt32(txtMob.Text.Trim()));

when i go for conversion i am getting "System.OverflowException: Value was either too large or too small for an Int32." exception

could anyone please provide solution for my problem???
Posted

Your mobile number contains some special characters in between.
Could be
1) Spaces 1234 56 78
2) Hyphens 1234-56-78

Thus when you try and convert this string into an integer for storing, even after the trim(), you will get an error.
 
Share this answer
 
Comments
Bhavani Ch 9-Apr-15 4:24am    
No, the mobile number which i have entered does not contain any spaces, Hyphens and special characters.. its a 10- digit number
Abhinav S 9-Apr-15 4:44am    
Ok. Try using Convert.ToIn64.

A phone number can be stored as a varchar and that will allow you to store special characters as well.
Bhavani Ch 9-Apr-15 7:39am    
Also Tried using Convert.ToIn64, that is throwing exception saying that cannot convert from string to long
I would suggest you change the type of the column in the database to nvarchar with a sufficient length. A mobile number doesn't need to be treated as an integer - you don't need to use it in calculations. If you want to store it without formatting (like braces, dashes and spaces) you can still remove that from the string before storing it.
 
Share this answer
 

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