我需要从数据库中随机选择昵称,并将这些昵称显示给多个标签。
我的代码在所有这些标签中只显示一个昵称,但我需要在按钮后点击随机昵称,数据库中的内容,在标签中显示。
void Button1Click(object sender, EventArgs e)
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=names.mdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT ID,nickname FROM names where ID=3 ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read()){
label1.Text=reader["nickname"].ToString();
label2.Text=reader["nickname"].ToString();
label3.Text=reader["nickname"].ToString();
label4.Text=reader["nickname"].ToString();
label5.Text=reader["nickname"].ToString();
label6.Text=reader["nickname"].ToString();
label7.Text=reader["nickname"].ToString();
label8.Text=reader["nickname"].ToString();
}
connection.Close();
}
表格的例子 http://greenlight.ucoz.lv/11cqsvX/ac_lb.png
到label1 nickname1, 标签2昵称26, 标签3昵称78, ...
请帮助我,抱歉我的英语不好:)
答案 0 :(得分:1)
我的想法是将SQL修改为select a random row,因为您当前的SQL将始终选择相同的行。通过迭代每个标签为每个标签执行此操作。
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=names.mdb";
connection.Open();
foreach (Control control in Controls)
{
if (control is Label)
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT nickname FROM names ORDER BY rnd(ID)";
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
control.Text = reader["nickname"].ToString();
}
}
connection.Close();
}
答案 1 :(得分:0)
得到答案,现在我的代码看起来
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=names.mdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT ID,nickname FROM names ORDER BY rnd(ID)";
foreach (Control control in Controls)
{
if (control is Label)
{
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
control.Text = reader["nickname"].ToString();
reader.Close();
}
}
connection.Close();
谢谢@MikeB