如何从DataGridView获取Button名并按Access数据库状态修改背景色
首先你得明白:你写的butttonn.BackColor之所以无效,是因为butttonn只是个字符串,不是真正的Button控件对象。得先通过名称找到对应的Button实例,再结合数据库查询结果设置颜色。
一、通过名称获取Button控件
情况1:Button直接在窗体上
用窗体的Controls.Find方法就能定位到控件:
string buttonName = "table" + c.ToString(); // 第二个参数true表示递归查找所有子控件 Button targetBtn = this.Controls.Find(buttonName, true).FirstOrDefault() as Button; if (targetBtn != null) { // 找到控件后就能修改属性了 }
情况2:Button在DataGridView的单元格中(比如DataGridViewButtonColumn)
需要从指定行/列的单元格里获取按钮对象:
int targetRowIndex = 0; // 替换成你要操作的行索引 DataGridViewButtonCell btnCell = dataGridView1.Rows[targetRowIndex].Cells[c] as DataGridViewButtonCell; if (btnCell != null) { // 这里可以设置单元格按钮的样式 }
二、结合Access数据库判断并设置颜色
先写一个方法,查询数据库里是否存在目标按钮名称:
private bool CheckButtonInDb(string buttonName) { // 替换成你的Access数据库连接字符串 string connStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=你的数据库路径.accdb;"; using (OleDbConnection conn = new OleDbConnection(connStr)) { conn.Open(); // 假设存储按钮名称的表是ButtonList,字段是BtnName string sql = "SELECT COUNT(*) FROM ButtonList WHERE BtnName = @BtnName"; using (OleDbCommand cmd = new OleDbCommand(sql, conn)) { cmd.Parameters.AddWithValue("@BtnName", buttonName); int count = (int)cmd.ExecuteScalar(); return count > 0; } } }
然后把获取控件和数据库查询结合起来:
针对窗体上的Button
string buttonName = "table" + c.ToString(); Button targetBtn = this.Controls.Find(buttonName, true).FirstOrDefault() as Button; if (targetBtn != null) { bool isExists = CheckButtonInDb(buttonName); targetBtn.BackColor = isExists ? System.Drawing.Color.Green : System.Drawing.Color.Red; }
针对DataGridView中的按钮单元格
int targetRowIndex = 0; DataGridViewButtonCell btnCell = dataGridView1.Rows[targetRowIndex].Cells[c] as DataGridViewButtonCell; if (btnCell != null) { string buttonName = "table" + c.ToString(); bool isExists = CheckButtonInDb(buttonName); btnCell.Style.BackColor = isExists ? System.Drawing.Color.Green : System.Drawing.Color.Red; // 必要时刷新DataGridView显示 dataGridView1.Refresh(); }
注意事项
- 数据库连接字符串要根据你的Access版本调整:旧版本(.mdb)用
Microsoft.Jet.OLEDB.4.0,新版本(.accdb)用Microsoft.ACE.OLEDB.12.0 - 确保拼接的
buttonName和数据库里存储的名称完全一致(大小写、空格都要匹配)
内容的提问来源于stack exchange,提问作者Abdullah Başaran
相关产品推荐
相关产品推荐

