Click here to Skip to main content
15,886,639 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i am validating whether the user enters in the textbox1 student id is there in the database or not.

for that code as follows;


C#
SCon.Con.Open();
       string str = "Select  count(*)  from Studdet where studid = '" + txt_Studid.Text.ToString() + "'";
       SqlCommand cmd = new SqlCommand(str, SCon.Con);
       int a = Convert.ToInt16(str);
       int count = (int)cmd.ExecuteScalar();
       if (count > 0)
       {
           Label4.Text = "Correct Student id";
           return;
       }
       else
       {
           Label4.Text = "InCorrect student id is there";
           return;
       }
          SCon.Con.Close();


in the run mode when i enters the student id in the textbox1 and click the button shows error as follows;

input string was not in a correct format


what is the problem in my above code please help me.

Regards,
Narasiman P.
Posted
Updated 30-Apr-13 21:21pm
v2

Before converting the string to int, make sure that the string is not null...
use like this
C#
int i = String.IsNullOrEmpty(str) ? -1 : Convert.ToInt16(str);
 
Share this answer
 
Remove that Single Quote
C#
SCon.Con.Open();
        string str = "Select  count(*)  from Studdet where studid = " + txt_Studid.Text.ToString() ;
        SqlCommand cmd = new SqlCommand(str, SCon.Con);
        int a = Convert.ToInt16(str);
        int count = (int)cmd.ExecuteScalar();
        if (count > 0)
        {
            Label4.Text = "Correct Student id";
            return;
        }
        else
        {
            Label4.Text = "InCorrect student id is there";
            return;
        }
               SCon.Con.Close();
 
Share this answer
 
v2
Hello
If you debug your project you find error on this line
int a = Convert.ToInt16(str);

because str have "
Select count(*) from Studdet where studid
"
which is never convert to int
please remove this line and execute this you get result
..



C#
SCon.Con.Open();
string str = "Select count(*) from Studdet where studid = '" + txt_Studid.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(str, SCon.Con);
int a = Convert.ToInt16(str);
int count = (int)cmd.ExecuteScalar();
SCon.Con.Close();
if (count > 0)
{
Label4.Text = "Correct Student id";
return;
}
else
{
Label4.Text = "InCorrect student id is there";
return;
}
</pre>



thanks 

and also closed connection before return because it will un-reachable code.
if problem persist please give me your reviews.,...
 
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