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"]);

Answers


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.

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(); 

Pretty sure you just wanna do:

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

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

Need Your Help

mysql select sum group by date

mysql select group-by

Quick question, I have the following table

What features would you like to see in a game programming DSL?

programming-languages language-design dsl

Me and my friend are in the first stages of creating a domain-specific language designed for game programming, for his thesis paper.