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