Reputation: 4570
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
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:
Upvotes: 4
Reputation: 35582
String UserNames;
if(reader["users"]!=null)
UserNames = (string)reader["users"];//or reader["users"].ToString();
Upvotes: 3
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
Reputation: 19656
Pretty sure you just wanna do:
String UserNames = reader["users"] as string;
Upvotes: 4