编译器错误消息:CS0021

时间:2012-01-24 14:40:23

标签: c# asp.net .net-3.5 asp.net-3.5

任何人都知道为什么以下不起作用?

C#:

public partial class Default : System.Web.UI.Page
{
    SqlConnection connection;
    SqlCommand command;
    SqlDataReader reader;

    protected void Page_Load(object sender, EventArgs e)
    {
        using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"]))
        {
            using (command = new SqlCommand("select col1, col2 from table1 where id = @id", connection))
            {
                command.Parameters.Add("@id", SqlDbType.Int, 3).Value = 1;
                connection.Open();

                using (reader = command.ExecuteReader())
                {
                    reader.Read();
                    Div1.InnerHtml = reader.Read["col1"].ToString();
                }
            }
        }
    }
}

HTML:

<div runat="server" id="Div1"></div>

错误:

Compiler Error Message: CS0021: Cannot apply indexing with [] to an expression of type 'method group'
Line 32: Div1.InnerHtml = reader.Read["col1"].ToString();

2 个答案:

答案 0 :(得分:9)

更改此

Div1.InnerHtml = reader.Read["col1"].ToString();

进入这个

Div1.InnerHtml = reader["col1"].ToString();

答案 1 :(得分:0)

因为您在SqlDataReader上应用了错误的索引器。 SqlDataReader

你可以这样尝试

 Div1.InnerHtml = reader["your ColumnName"].ToString();

这里提供了为什么会引发异常的完整细节ERRor cs0021