TechGuy
TechGuy

Reputation: 4570

Cannot apply indexing with [] to an expression of type 'method group'

After the query execution the result I need to take is UserNames part.

I'm gettting an error: Cannot apply indexing with [] to an expression of type 'method group'

public class ProcessInput
{
    string connectionString = (string)ConfigurationSettings.AppSettings["myConString"];
    private string msg_arr;
    string username = null;

    private void MooseSeenInput(string MobileNo, string Date, string odd, params Array[] msg_arr)
    {
        SqlConnection conn = new SqlConnection(myConString);
        conn.Open();
        SqlCommand com = new SqlCommand("SELECT * FROM Users as users WHERE UserName=@UserName AND State!='1' AND State!='4'", conn);
        com.Parameters.AddWithValue("@UserName", UserName);
        // com.ExecuteNonQuery();
        using (SqlDataReader reader = com.ExecuteReader())
        {
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    String UserNames = (reader.Read["users"]);
                }
            }
        }
    }
}

Error occurred at line:

String UserNames = (reader.Read["users"]);

Upvotes: 1

Views: 28532

Answers (4)

Adam Houldsworth
Adam Houldsworth

Reputation: 64557

Your error is a compiler error as you were trying to apply index syntax onto a method call, which in C# involves brackets.

The SqlDataReader does expose an indexer, but it is on the reader itself, not a method member:

string username = (string)reader["users"];

This is how I tend to style this code:

using (SqlDataReader reader = com.ExecuteReader())
{
    int userOrd = reader.GetOrdinal("users");

    while (reader.Read())
    {
        string username = reader.GetString(userOrd);
    }
}

Note that I ask the reader for the ordinal prior to iterating an unknown number of records. This is good for two reasons:

  1. I have cached the ordinal once and use it many times, this helps performance.
  2. I have not hard-coded the ordinal so if someone were to change the column position in the result-set in the stored procedure / script, my code would continue to work.

Upvotes: 4

Rab
Rab

Reputation: 35582

String UserNames;
if(reader["users"]!=null)     
UserNames = (string)reader["users"];//or reader["users"].ToString();

Upvotes: 3

Steve
Steve

Reputation: 216363

Use

   String UserNames = reader.GetString(0); 

And as @leppie pointed in its comment, you could also use the field name as indexer
So supposing the field is named users you could also write this:

  String UserNames = reader["users"].ToString(); 

Upvotes: 6

Dave Bish
Dave Bish

Reputation: 19656

Pretty sure you just wanna do:

String UserNames = reader["users"] as string;

Upvotes: 4

Related Questions