I have a problem with template fields where I create a link for data in a row in Grid View. When for a first time i run my page it works fine, but later when i hide some other columns in that grid view and i want to back for my first view (I show all columns that were hidden) mine code behind throw null pointer exception. But Query for that grid is the same and the columns are the same. It always happens when i hide and add some columns to my code.
Please if u can help me with that i will be very grateful.
<asp:TemplateField HeaderText="zz" Visible="False">
<ItemTemplate>
<asp:Label ID="Label_typ" runat="server"
Text='<%# Eval("TYP") %>'></asp:Label>
<br> </br>
</ItemTemplate>
</asp:TemplateField>
Code behind witch complicates my all my code. Without it, it works fine.
if (actualYear.Equals(dd_rok22.SelectedValue))
{
int numberOfWeek = 1;
for (int i = Convert.ToInt32(actualMonth); i <= 12; i++)
{
GRID_VIEW_MAKRO.Columns[i + 7].Visible = false;
if (i == Convert.ToInt32(actualMonth))
{
int numberColumnActual = i;
BoundField field2 = new BoundField();
GRID_VIEW_MAKRO.Columns.Insert(numberColumnActual + 3, field2);
for (int j = 1; j <= weekNumberActualMonth; j++)
{
BoundField field = new BoundField();
GRID_VIEW_MAKRO.Columns.Insert(numberColumnActual + 3, field);
field.HeaderText = "M" + actualMonth + "_T" + numberOfWeek;
field.DataFormatString = "{0:###,###}";
numberColumnActual++;
numberOfWeek++;
}
for (int numberOfWeekPrevious = numberOfWeek; numberOfWeekPrevious <= 4; numberOfWeekPrevious++)
{
BoundField field = new BoundField();
GRID_VIEW_MAKRO.Columns.Insert(numberColumnActual + 2, field);
field.HeaderText = "M" + previousMonth2 + "_T" + numberOfWeek;
field.DataFormatString = "{0:###,###}";
numberOfWeek++;
numberColumnActual++;
}
}
}
}
And the exception shows when i create Label witch have null value because of TemplateField have null value.
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string mregion= DataBinder.Eval(e.Row.DataItem, "MAKRO_NAME").ToString();
Label lbl = (Label)e.Row.FindControl("Label_typ");
string CellValue = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ROK"));
//it cannot Trim me null value..
string ID = lbl2.Text.Trim() + '_' + lbl3.Text.Trim();
e.Row.Attributes.Add("onclick", "top.location.href='report_se.aspx?nazwa=" + ID + "&ye=" + CellValue + "';");
}
}
1) Making some field visible false should not create any error at the run time.
2) For null pointer exception, I think you are trying to typecast null values. If any of your fields contain null values then it is advisable to check it before typecasting it.