在将数据源(可能为空,具体取决于具体情况)绑定到gridview时,我得到一个nullreference异常。我该如何解决这个问题?
if (!IsPostBack)
{
SetGridView();
}
private void SetGridView()
{
GroupTelephoneNumberManagementGridView.DataSourceID = odsGroupTelephoneNumbers.ID;
GroupTelephoneNumberManagementGridView.DataBind();
}
protected void GroupTelephoneNumberManagementGridView_DataBound(object sender, EventArgs e)
{
var gridView = (GridView)sender;
gridView.BottomPagerRow.Visible = true;
}
protected void GroupTelephoneNumberManagementGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Check for the row type, which should be data row
if (e.Row.RowType == DataControlRowType.DataRow)
{
var groupPhoneNumber = (GroupPhonenumber)e.Row.DataItem;
var activateTelephoneOption = (RadioButtonList)e.Row.FindControl("activateTelephoneOption");
//Set a unique value as data-attribute in RadioButtonList
activateTelephoneOption.Attributes.Add(DataTelephonenumber, groupPhoneNumber.Phonenumber);
activateTelephoneOption.Attributes.Add(DataUserId, groupPhoneNumber.UserId);
//fill the name column in the gridview with firstname and lastname
var nameLabel = (Label)e.Row.FindControl("nameLabel");
nameLabel.Text = groupPhoneNumber.FirstName + " " + groupPhoneNumber.LastName;
//Get if the number is activated or not
activateTelephoneOption.SelectedIndex = groupPhoneNumber.Activated ? 1 : 0;
// Remove the landcode form the phonenumber
var numberLabel = (Label)e.Row.FindControl("numberLabel");
numberLabel.Text = PhoneNumberWithoutlandCode(groupPhoneNumber.Phonenumber);
}
}
注意:这已经生效并且正常工作,但在某些情况下,数据源应为null,因为客户没有要绑定的任何数字。 (在那种情况下,我得到一个空引用异常,所有其他情况完美地工作)。