开发者

Silverlight 4 C# - How to catch a NullReferenceException?

开发者 https://www.devze.com 2023-02-04 04:59 出处:网络
Here\'s my code: if (dataGrid.CurrentColumn.DisplayIndex == 1) txtArticle.Text += \" \" + ((TextBlock)dataGrid.CurrentColumn.GetCellContent(dataGrid.SelectedItem)).Text + \" \";

Here's my code:

if (dataGrid.CurrentColumn.DisplayIndex == 1)
            txtArticle.Text += " " + ((TextBlock)dataGrid.CurrentColumn.GetCellContent(dataGrid.SelectedItem)).Text + " ";

This works beautifully if I've already populated the datagrid with something, but throws a NullReferenceException if it has yet to be filled with anything. I tried an if statement to check for a null value - if (dataGrid.CurrentColumn.DisplayIndex == n开发者_JS百科ull), but that had no effect.

How do I handle this?

Thanks,

-Sootah


I would assume that it is dataGrid.CurrentColumn that is null, not dataGrid.CurrentColumn.DisplayIndex, so that is what you should check in the if statement:

if (dataGrid.CurrentColumn != null && dataGrid.CurrentColumn.DisplayIndex == 1)
    txtArticle.Text += " " + ((TextBlock)dataGrid.CurrentColumn.GetCellContent(dataGrid.SelectedItem)).Text + " ";


I think @Fredrik meant to type:

if (dataGrid.CurrentColumn != null && dataGrid.CurrentColumn.DisplayIndex == 1)
0

精彩评论

暂无评论...
验证码 换一张
取 消