user347640
user347640

Reputation: 223

c# Sqlcommand error

foreach (string str in TestWords)
{
  //spam
  SqlCommand cmd6 = new SqlCommand("select count from keys,files,folders where keys.fileid=files.id and keys.kname='" + str + "' and files.spam=1 and folders.id<>" + FolIter + " and files.folderid<>" + FolIter + " and files.id='" + s[0].ToString + "'", cn);
  int i6 = Convert.ToInt16(cmd6.ExecuteScalar());
  double temp = Convert.ToDouble((i6 + 1) / (i7 + i8));
  //non spam

  **error**

  SqlCommand cmd9 = new SqlCommand("select count from keys,files,folders where keys.fileid=files.id and keys.kname='" 
    + str 
    + "' and files.spam=0 and folders.id<>"
    + FolIter
    + " and files.folderid<>" 
    + FolIter 
    + " and files.id='" 
    + s[0].ToString 
    + "'", cn);
  int i9 = Convert.ToInt16(cmd9.ExecuteScalar());
  temp2 = Convert.ToDouble((i9 + 1) / (i7 + i8));
  Sdoc = Convert.ToDouble(Sdoc * temp);
  NsDoc = Convert.ToDouble(NsDoc * temp2);
}

The error iam getting is:Operator '+' cannot be applied to operands of type 'string' and 'method group'

Upvotes: 0

Views: 436

Answers (3)

Larry
Larry

Reputation: 18031

As Nix, Femaref and Azhar mentioned, .ToString() is the typo that triggers the error message.

May I suggest to use parameters instead of string concatenation ? This way:

SqlCommand cmd9 = new SqlCommand("select count from keys,files,folders where keys.fileid=files.id and keys.kname=@name and and files.spam=0 and folders.id<>@FolIter and files.folderid<>@FolIter and files.id=@s0", cn);

cmd9.Parameters.Add(new SqlParameter("@name", str));
cmd9.Parameters.Add(new SqlParameter("@FolIter", FolIter));
cmd9.Parameters.Add(new SqlParameter("s0", s0));

By this way, ADO.NET will deal with your variable as is, you wont have to convert them to string to use concatenation, and you wont be exposed to a SQL injection risk.

Upvotes: 5

Azhar
Azhar

Reputation: 20670

You are using method ToString() as Property

change s[0].ToString -> s[0].ToString()

Remember C# does not allow it.

Upvotes: 2

Femaref
Femaref

Reputation: 61427

You have to call the method:

s[0].ToString()

Upvotes: 8

Related Questions