根据数据库信息动态更改按钮图像

时间:2012-12-05 20:52:43

标签: c# winforms button sql-server-ce

我正在尝试根据数据库中的状态更改多个按钮图像。 如果我得到任何状态“0”,我应该将按钮图像更改为“忙”图像,因为默认图像是“免费”图像。

所以我的问题是:如何通过变量名更改按钮?

我现在有这个代码(我知道错了):

private void checkSuites()
{
    SqlCeCommand checkSuite = new SqlCeCommand("SELECT * FROM RentSessionLog WHERE State='0'", mainConnection);

    SqlCeDataReader readSuite = checkSuite.ExecuteReader();
    int suiteIndex;
    string suitePath = "suite" + suiteIndex;

    while (readSuite.Read())
    {
        suiteIndex = Convert.ToInt32(readSuite["SuiteNum"]);
        suitePath.Image = NewSoftware.Properties.Resources.busySuiteImg;
    }
}

3 个答案:

答案 0 :(得分:2)

这很简单:

while (readSuite.Read())
{
    suiteIndex = Convert.ToInt32(readSuite["SuiteNum"]);
    switch(suiteIndex)
    {
    case 0:
       {
           suitePath.Image = NewSoftware.Properties.Resources.busySuiteImg;
           break;
       }
    default:
       {
           suitePath.Image = NewSoftware.Properties.Resources.freeSuiteImg;
       }
    }
}

编辑:

我使用开关的原因是为了防止您将来出现其他状态。你有“忙”和“免费”,但也可能有“保留”,你可能想要进一步的条件,只是在一个简单的if else if序列中被混淆。

答案 1 :(得分:1)

我相信您需要使用this.Controls.Find(suitePath, true)将字符串转换为控件。我假设"suite" + suiteIndex是每个按钮的.Name

string suitePath = "suite" + suiteIndex;
Button suiteButton = this.Controls.Find(suitePath, true);
suiteButton.Image = ...

See more details about Controls.Find

或者为了更快地访问,您可能希望在其中保留Dictionary<int, Control>每个按钮。

答案 2 :(得分:0)

我知道了!使用词典作为胸腺嘧啶说:

                public void checkSuites()
    {
        Dictionary<int, Control> btnList = new Dictionary<int, Control>();
        btnList.Add(1, suite1);
        btnList.Add(2, suite2);
        btnList.Add(3, suite3);
        btnList.Add(4, suite4);
        btnList.Add(5, suite5);
        SqlCeCommand checkSuite = new SqlCeCommand("SELECT * FROM RentSessionLog WHERE State='0'", mainConnection);

        SqlCeDataReader readSuite = checkSuite.ExecuteReader();
        while (readSuite.Read())
        {
            int suiteIndex = Convert.ToInt32(readSuite["SuiteNum"]);
            string suitePath = "suite" + suiteIndex;
            foreach (Button key in btnList.Values)
            {
                if (key.Name == suitePath)
                {
                 key.Image = NewSoftware.Properties.Resources.busySuiteImg;
                }
            }

            }


    }

谢谢所有帮助过的人:D

相关问题