1

我是 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();
    }
}
4

1 回答 1

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需要 a using,并且非常不清楚在哪里定义cmd,但这也需要 ausing并且不应该共享(它应该在此方法范围内)。我将重写为:

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);
            }
       }
   }
}
于 2012-10-19T13:23:14.293 回答