获取CS1518:预期的类,委托,枚举,接口或结构错误

时间:2012-10-19 13:19:06

标签: c# asp.net mysql class

我是C#的新手,我正在努力学习(最近我一直在问几个问题 - 我唯一的编程知识是Python,PHP和Javascript)。无论如何,我在网上找到了一些如何在C#中生成选项列表的例子,我正在尝试使用/修改它们以适应我现有的代码。结果出现了预期的类错误 - 但我正在创建一个类!这是我的代码:

private void PeerReview()
{

            MySqlConnection connection;
            string connStringName = "server=localhost;database=hourtracking;uid=username;password=password";
            connection = new MySqlConnection(connStringName);

            cmd.CommandText = "select name from peer_review_info where active_status=1";
            cmd.Connection = connection;
            connection.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    ListItem item = new ListItem();
                    item.Text = sdr["peerrevid"].ToString();
                    item.Value = sdr["peerrevid"].ToString();
                    item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
                    chkPeerRev.Items.Add(item);
                }
            }
           connection.Close();
        }
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.PeerReview();
    }
}

1 个答案:

答案 0 :(得分:2)

你有很多关闭括号。应该是:

private void PeerReview()
{    
    MySqlConnection connection;
    string connStringName =
        "server=localhost;database=hourtracking;uid=username;password=password";
    connection = new MySqlConnection(connStringName);

    cmd.CommandText = "select name from peer_review_info where active_status=1";
    cmd.Connection = connection;
    connection.Open();
    using (SqlDataReader sdr = cmd.ExecuteReader())
    {
        while (sdr.Read())
        {
            ListItem item = new ListItem();
            item.Text = sdr["peerrevid"].ToString();
            item.Value = sdr["peerrevid"].ToString();
            item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
            chkPeerRev.Items.Add(item);
        }
   }
   connection.Close();
}

嗯,实际上它需要更多的变化; connection需要using非常不清楚cmd的定义位置,但也需要using且不应共享(它应该是这个方法的范围)。我会改写为:

private void PeerReview()
{    
    string connStringName = SomethingExternal.GetConnectionString();

    using(var connection = new MySqlConnection(connStringName))
    using(var cmd = connection.CreateCommand())
    {
        cmd.CommandText =
            "select name from peer_review_info where active_status=1";
        connection.Open();
        using (var sdr = cmd.ExecuteReader())
        {
            while (sdr.Read())
            {
                ListItem item = new ListItem();
                item.Text = sdr["peerrevid"].ToString();
                item.Value = sdr["peerrevid"].ToString();
                item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
                chkPeerRev.Items.Add(item);
            }
       }
   }
}