How to write a method returning string value?

VAer-4038 771 Reputation points
2021-01-19T22:04:32.67+00:00

Take below code for example, how can I return my first name? How to complete the code?

Thanks.

        public static string MyFirstName (string userID)
        {
            using (OdbcConnection Cn = new OdbcConnection(GlobalVariables.DatabaseConnectionString)) //Access database
            {
                Cn.Open();
                OdbcCommand cmd = Cn.CreateCommand();
                cmd.CommandText = "SELECT FirstName FROM TableUser WHERE Username = '" + userID + "'";
                OdbcDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                   //how to return a string
                } 
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("My first name in database is: " + GlobalVariables.MyFirstName(Environment.UserName));

        }
Developer technologies Windows Forms
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 90,681 Reputation points
    2021-01-19T22:39:31.167+00:00

    For example :

    public static string MyFirstName (string userID)
    {
            string sReturnString = null;
        using (OdbcConnection Cn = new OdbcConnection(GlobalVariables.DatabaseConnectionString)) //Access database
        {
            Cn.Open();
            OdbcCommand cmd = Cn.CreateCommand();
            cmd.CommandText = "SELECT FirstName FROM TableUser WHERE Username = '" + userID + "'";
            OdbcDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                sReturnString = (string)reader.GetValue(0);
                break;
            } 
         }
         return sReturnString;
    }
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.