Click here to Skip to main content
15,894,405 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a connection in a DAL to SQL server. Using this connection I am trying to read the query. I have tried using ExecuteReader() and ExecutreNonQuery() with no luck.
Here is my code:

C#
      private void button1_Click(object sender, EventArgs e)
        {
                    try{
            var cn = new Connection_Handler();
            string input = selectinput.Text;
            string reader = cn.Execute_SQL(input).ToString();
            MessageBox.Show(reader);
                        }
            catch(Exception ex){
                MessageBox.Show(ex.Message);
            }
}
    class Connection_Handler
    {
        SqlConnection cn;
        void ConnectiontoSQL()
        {
            string str = "server=xxx; database=jobSearch; user=sa; password=xxx";
            cn = new SqlConnection(str);
            cn.Open();            
        }
        public int Execute_SQL(string select)
        {
            ConnectiontoSQL();
            string Query = "select " + select + " from jobSearch where searchID = 1";
            SqlCommand cmd = new SqlCommand(Query, cn);
            SqlDataReader reader = cmd.ExecuteReader();
            return Convert.ToInt32(reader);
        }
    }


my error message is "unable to cast object of type 'sqldatareader' to type 'iconvertible' "
Posted

1 solution

You can use reader.GetInt32() but should check if it's NULL. If not sure type of data field best to get as a string and parse it as an Int32.
 
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