开发者

Cannot convert method group 'Read' to non-delegate type 'bool'

I am trying to use SqlDataReader to check if a entry exists. If it exists, it will return the ID, else it will return false. When I try to compile, I'm getting the error "Cannot convert method group 'Read' to non-delegate type 'bool'. I have been following an example I found in VB, but it seems the translation may not be correct.

private string checkProfileExists()
{
    string strReturn = "False";
    string strSql = ("SELECT ID FROM tblInformation WHERE txtUsername=@UserName " + 
        "AND TrackingID=@TrackingID");
    string strConn = ConfigurationManager.ConnectionStrings["WEM_PassWord_Reset"].
        ConnectionString;


    开发者_开发知识库SqlConnection objConn = new SqlConnection(strConn);
    SqlCommand objCmd = new SqlCommand(strSql, objConn);

    objCmd.Parameters.AddWithValue("@Username", txtUsername.Text);
    objCmd.Parameters.AddWithValue("@TrackingID", txtTrackingID.Text);

    try
    {
        objConn.Open();
        System.Data.SqlClient.SqlDataReader rdr = objCmd.ExecuteReader();

        if (rdr.Read)
        {
            strReturn = rdr("ID").ToString;
        }
        else
        {
            strReturn = "False";
        }
    }
    catch (Exception ex)
    {
        lblErrorMessage.Text = ex.ToString();
    }
    finally
    {
        objConn.Close();
        objCmd = null;
    }

    return strReturn;
}


When you see the phrase 'method group' in a C# error, one explanation to consider is that you have omitted the parentheses () from a method that takes no arguments. In this case, the method is Read on your DataReader.

When the compiler sees Read (with no parentheses), it thinks you are talking about the method itself, as if trying to assign it to a delegate, say. Whereas what you actually want to do is invoke the method - to do this, in C#, you must give the list of arguments (which in this case is empty), thus: Read().


if (rdr.Read())
{
    strReturn = rdr["ID"].ToString();
}


The () for method invocation of parameterless methods are not optional in C#. Without the parentheses the the expression identifies the method(group) and not its result value. This behavior makes the grammar much less ambiguous, especially for methods that return delegates.

The first reaction of a C# programmer when he sees "Cannot convert method group '...' to non-delegate type '...'" is usually "Oh I forgot my () for invocation".


Seeing your source I highly recommend to use the using statement for both the SqlConnection AND the SqlDataReader.

If you do NOT Close the reader, the garbagecollection moment will decide when the reader finalizes. You can bring SqlServer DOWN when you do not know that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜