根据数据库更改按钮图像

时间:2017-04-24 17:51:45

标签: c# sql sql-server

我有一个表单,其中包含引用表格的按钮,而按钮代表表格。默认按钮图像是免费的,我希望按钮图像根据数据库表“free”或“busy”中的值进行更改,我知道我的代码中存在错误。

如何让它发挥作用?

编辑:

我已经用默认的股票按钮替换了自定义按钮,现在它什么都没有,我检查了查询的结果,这是正确的,但没有任何变化,没有错误。

我的表格如下:

| tablenum | tabestatusint |
|----------|---------------|
| 1        | 0             |
| 2        | 1             |
| 3        | 1             |

因此如果tabestatusint0,则应更改图片

以下是我的尝试:

public void checkSuites()
{
  Dictionary<int, Control> btnList = new Dictionary<int, Control>();
  btnList.Add(1, Button1);
  btnList.Add(2, Button2);

  SqlCommand checkSuite = new SqlCommand(
                          "SELECT tablestatusint FROM tablesstatustbl", cn);
  SqlDataReader readSuite = checkSuite.ExecuteReader();
  while (readSuite.Read())
  {
    int suiteIndex = Convert.ToInt32(readSuite["tblstatusint"]);
    string suitePath = "tblstatusint" + suiteIndex;
    foreach (Button key in btnList.Values)
    {
      if (key.Name == suitePath)
      {
        key.Image = My_Café_Manger.Properties.Resources.tablesbusy;
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

首先,您不需要迭代字典来访问正确的按钮。这就是字典的重点。其次,调用当前元素&#39;键&#39;令人困惑,因为它暗示它是字典键,它不是。第三,你要比较你的按钮的名称(我可以看到你设置的那个)与字符串&#34; tblstatusintX&#34;其中X是数据库中的值。第四,suiteIndex名称错误,因为我认为它是真/假状态值而不是索引。第五,我认为你的第二列名称中有拼写错误,我认为应该是#table;表格&#39;。请注意丢失的字母&#39; l&#39;在你的问题。最后,您还缺少SQL查询中的tablenum列。

我认为你需要这样的东西:

SqlCommand checkSuite = new SqlCommand("SELECT tablenum, tablestatusint FROM tablesstatustbl", cn);
SqlDataReader readSuite = checkSuite.ExecuteReader();
while (readSuite.Read())
{
  int status = Convert.ToInt32(readSuite["tblstatusint"]);
  if (status == 1)
  {
    // I have separated the dictionary access and image assignment into two lines for readability
    int buttonNum = ConvertToInt32(readSuite["tableNum"]);
    btnList[buttonNum].Image = My_Café_Manger.Properties.Resources.tablesbusy;
  }
}

这非常&#34; aircode&#34;但它应该让你再次去。您可能还想查看this问题。

相关问题