【问题标题】:MySQL reader usage C#MySQL阅读器使用C#
【发布时间】:2011-11-16 19:11:49
【问题描述】:

我在从 MySql.Data.MySqlClient 理解 MySql 阅读器方面遇到了一些问题

这是我的代码:

while (reader.Read())
{
    documentButtons = new RadioButton[3];
    for (int i = 0; i < 3; i++)
    {
        documentButtons[i] = new RadioButton();
        documentButtons[i].Text = reader["name"].ToString() + " " + (i + 1);

        Console.WriteLine(reader["name"].ToString());

        documentButtons[i].Location = new System.Drawing.Point(10, 10 + i * 20);
        this.Controls.Add(documentButtons[i]);
    }
}
Console.ReadLine();

这会生成 3 个带有文本的单选按钮:“Dokument1 1”、“Dokument1 2”、“Document1 3” 正如您可能看到的,我希望“Dokument”后面的数字等于其后面的数字。 (我在数据库中的前 3 个条目是“Dokument1”、“Dokument2”和“Dokument3”。在我的控制台中,“Dokument1”、2 和 3 都出现了 3 次。我怎样才能让它在合适的单选按钮?

【问题讨论】:

  • 如果你想要的只是三个单选按钮,为什么还要有 for 循环?您正在为每个数据库记录构建三个,看起来像。

标签: c# mysql sqldatareader


【解决方案1】:

我不确定我是否完全理解您的问题,但如果您只想为返回的每一行返回一个 RadioButton,以下代码应该可以工作:

documentButtons = new RadioButton[3];
int i = 0;
while (i <= 3 && reader.Read()) { // make sure we don't get an IndexOutOfRangeException
  documentButtons[i] = new RadioButton();
  documentButtons[i].Text = reader["name"].ToString() + " " + (i + 1);

  Console.WriteLine(reader["name"].ToString());

  documentButtons[i].Location = new System.Drawing.Point(10, 10 + i * 20);
  this.Controls.Add(documentButtons[i]);

  ++i;
}

【讨论】:

  • 我喜欢你几乎逐字逐句地贴出我正在输入的答案。 :)
  • @reallyJim:你必须输入 FASTER! ;)
  • 啊,那是我一直在寻找的读者和“我”,非常感谢 :) 就像一个魅力一样谢谢你 :D
猜你喜欢
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 2014-09-13
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多