2016-03-28 92 views
-2

我想在运行时在WPF中设置按钮的背景颜色(名称:b0,b1,b2,b3,b4,b5,b6,b7,b8,b9)。在运行时设置WPF中按钮的背景颜色

颜色名称从Red数据库获取。但它给我System.NullReferenceExceptionn:对象引用不设置到对象的实例

private void ButtonBgColor() 
{ 
string qryBgColor = "select Name from lookup where code in (select VALUE from qSettings where name='BUTTON_BG_COLOR') and type='BgColor'"; 
try 
{ 
sqlConnection.Open(); 
sqlCommand = new SqlCommand(qryBgColor, sqlConnection); 
sqlDataReader = sqlCommand.ExecuteReader(); 
if (sqlDataReader.Read()) 
{ 
string BUTTON_BG_COLOR = sqlDataReader["Name"].ToString(); 
Button[] b = new Button[9]; 
for (int i = 0; i < b.Length; i++) 
{ 
var textBlock08 = (TextBlock)b[i].Template.FindName("myTextBlock", b[i]); 
textBlock08.Background = (System.Windows.Media.SolidColorBrush)new System.Windows.Media.BrushConverter().ConvertFromString(BUTTON_BG_COLOR); 
} 
} 
} 
catch (Exception exp) 
{ 
MessageBox.Show(exp.ToString(), "Button Background Color Exception"); 
} 

谁能帮我解决这个问题呢?

在此先感谢

回答

1

您还没有分配任何东西给b。这只是一个空阵列。因此,调用b [i]将始终导致null-ref。

+0

它在循环,它可能是NULL? –

+0

你的数组不是null,但数组内的每个元素都是null。 – Jace

+0

b0是按钮的名称 –