2017-04-24 61 views
0

我有一个表单,其中包含引用表的按钮并且按钮表示表。默认的按钮图像是免费的,我希望按钮图像根据数据库表中的“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

名称'btnList'与它的类型不是很相关 – dcg

+0

@Renato Parreira你能帮我解决这个问题吗 –

回答

1

首先你不需要迭代字典以访问正确的按钮。这是字典的重点。其次调用你当前的元素“关键”是令人困惑的,因为它意味着它是字典关键。第三,你将比较你的按钮的名称(我看不到你曾经设置过)与字符串“tblstatusintX”,其中X是来自数据库的值。第四套房指数被错误地命名,因为我认为它是真实/虚假的状态值而不是索引。第五,我认为你的第二列名称中的错字应该是'tablestatusint'。注意你的问题中缺失的字母'l'。最后,您还错过了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; 
    } 
} 

这是非常“aircode”,但它应该让你去一次。您可能还想查看this的问题。

+0

首先非常感谢你的回答和你的时间我用词典来提高性能,因为我可能会有很多按钮..我仍然有红色下划线下:readSuite [“tableNum”]说:不能从对象转换为int –

+0

@Ahmed_Zoeil是的,我后来意识到你为什么使用字典和修改我的答案。尝试'readSuite [“tableNum”]。值' – Caltor

+0

我stil得到红色下划线错误。'。value'说:对象不包含值的定义和方法值的扩展接受对象的第一个参数可以找到 –