Gridview OnRowEditing event handler not firing - asp.net

I have a gridview that uses list as it's datasource, this list is populated using entity framework and passed to my method where this data is binded to my grid view control. I seem to be having a problem with editing a row.
On designer I have added properties for the grid view to have a OnRowEditing handler and I have added a button for edit but my OnRowEditing event handler isn't firing. The breakpoint doesn't hit.
My Gridview control
<asp:GridView runat="server"
ID="grdNotes"
OnRowCommand="grdNotes_RowCommand"
AllowPaging="true"
AllowSorting="true"
EnableTheming="true"
AutoGenerateColumns="false"
OnPageIndexChanging="grdNotes_PageIndexChanging"
OnSorting="grdNotes_Sorting"
AlternatingRowStyle-BorderColor="Yellow"
PageSize="3"
AlternatingRowStyle-BackColor="Yellow"
OnRowEditing="grdNotes_RowEditing"
OnRowDeleting="grdNotes_RowDeleting"
DataKeyNames="NotesID" >
<Columns>
<asp:BoundField HeaderText="Title" DataField="NotesTitle" SortExpression="NotesTitle">
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="Text" DataField="NotesText" SortExpression="NotesText">
<ItemStyle Height="20px" Width="250px" />
</asp:BoundField>
<%-- <asp:ButtonField CommandName="EditRow" DataTextField="Edit" HeaderText="Edit" />
<asp:ButtonField CommandName="DeleteRow" DataTextField="Delete" HeaderText="Delete" />--%>
<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />
<asp:CommandField ShowCancelButton="true" />
</Columns>
</asp:GridView>
Code behind
I retrieve the data from entity framework on Page_Init. I also have global variables
private List<NotesModel> list = new List<NotesModel>();
NotesModel nm = new NotesModel();
protected void Page_Init(object sender, EventArgs e)
{
NoteSearch ns = new NoteSearch(Business.ContextHelper.CurrentContext);
string[] urlArray = Request.RawUrl.Split('/');
string t = urlArray[4];
string[] relatedID = t.Split('=');
if (!IsPostBack)
{
// urlArray[3] is profile type , relatedID[1] is ID
list = ns.GetBasicNoteResults(nm, urlArray[3], relatedID[1]);
}
else
{
urlArray = Request.UrlReferrer.AbsoluteUri.Split('/');
t = urlArray[6];
relatedID = t.Split('=');
list = ns.GetBasicNoteResults(nm, urlArray[5], relatedID[1]);
}
GenerateGrid(list);
btnNotes.Text = "Notes: " + list.Count.ToString();
}
My binding method
private void GenerateGrid(List<NotesModel> list)
{
grdNotes.DataSource = list;
grdNotes.DataBind();
int count = grdNotes.Rows.Count;
//// Hide headers we don't want to expose
//grdNotes.HeaderRow.Cells[0].Visible = false;
//grdNotes.HeaderRow.Cells[3].Visible = false;
//grdNotes.HeaderRow.Cells[4].Visible = false;
//grdNotes.HeaderRow.Cells[5].Visible = false;
//for (int i = 0; i < count; i++)
//{
// // Loop through rows and hide cells
// grdNotes.Rows[i].Cells[0].Visible = false;
// grdNotes.Rows[i].Cells[3].Visible = false;
// grdNotes.Rows[i].Cells[4].Visible = false;
// grdNotes.Rows[i].Cells[5].Visible = false;
//}
// Finally add edit/delete buttons for these click event handlers
}
One final thing I noticed is when I hover over the edit row linkbutton, there is no query string, same with my paging at the bottom of the grid and my headers. Clicking on any of the grid controls take the user to:
http://localhost:8192/website/Company
and not
http://localhost:8192/website/Company/Advertiser/?id=8879
Summary
My gridview event handlers don't fire. Have I missed something to make this work?

You need to move this code:
GenerateGrid(list);
Inside the if(!Page.IsPostBack) block.
Each time your page posts back to the server (e.g. when you click the edit button), this code is rebuilding your GridView back to it's original state. This doesn't allow the RowEditing event to even occur, because you've essentially destroyed it and re-added it during Init (before it has a chance to occur).
Looking at your code some more, it appears you are using IsPostBack to determine the contents of the grid. You will need to modify that logic in order for this to work. Perhaps you can examine the contents of the query string being passed (or the number of / characters in the query string) to decide what parameters to pass to the GetBasicNoteResults method.
Your code will basically look like this:
if (!IsPostBack)
{
if (Some logic to decide what parameters to pass)
{
list = ns.GetBasicNoteResults(nm, urlArray[3], relatedID[1]);
}
else
{
list = ns.GetBasicNoteResults(nm, urlArray[5], relatedID[1]);
}
GenerateGrid(list);
}

Related

asp.net check if checkbox in gridview is checked

Gridview with a select-button, a boundfield and a checkbox. Binding the data to the gridview works fine. (the data in the DB has an NVARCHAR column for the bounfield and a BIT column for the checkbox.
When selecting a row via the 'Select' button, an event in code-behind is fired, and data from the 2 cells from the gridview are copied to 2 controls on the page: a textbox and checkbox.
The first works ok and I have no clue as to how to check if the checkbox in the gridview is checked or not. I need to know that so that I can populate other checkbox control accordingly.
(before I paste my code: I just spent some 12 hours searching for a solution here in SO and elsewhere. None of the numerous entries helped. So please bear with me...)
<asp:GridView ID="grv_Test1" runat="server" CssClass="myGrid"
AutoGenerateColumns="False" DataKeyNames="Test1_First_Name"
OnRowCommand="grv_Test1_RowCommand">
<Columns>
<asp:CommandField SelectText="sel'" ShowSelectButton="True" ControlStyle-CssClass="btn btn-primary myBtn-xs">
</asp:CommandField>
<asp:BoundField DataField="Test1_First_Name" HeaderText="Name"><HeaderStyle Width="85px" />
</asp:BoundField>
<asp:CheckBoxField DataField="Test1_Active" HeaderText="Active">
</asp:CheckBoxField>
</Columns>
<HeaderStyle CssClass="myGridHeader" />
</asp:GridView>
Code behind:
int my_Data_From_Grid = Convert.ToInt32(e.CommandArgument);
txb_Test1_Name.Text = grv_Test1.Rows[my_Data_From_Grid].Cells[1].Text; // this works
cbx_Test1_Active.Text = grv_Test1.Rows[my_Data_From_Grid].Cells[2].Text; // NOT working
if (Convert.ToString(grv_Test1.Rows[my_Data_From_Grid].Cells[2].Text) == "1") // NOT working either
{ cbx_Test1_Active.Checked = true; }
else
{ cbx_Test1_Active.Checked = false; }
if (Convert.ToString(grv_Test1.Rows[my_Data_From_Grid].Cells[2].Text) == "True") // NOT working either
{ cbx_Test1_Active.Checked = true; }
else
{ cbx_Test1_Active.Checked = false; }
Here is what I got when selecting Michael's row:
In the gridview Michael is "Active", and I need the checkbox at the top to be 'checked'.
How can it be done...? Thnaks a lot.
With CheckBoxFields and CheckBoxes, you need to get the Checked value to know whether or not it was actually checked. The Text value is actually another property of the CheckBox (see MSDN). You sometimes see this text to the left or right of the CheckBox itself.
So what you need to do is first get the CheckBox. Then use the Checked property of that CheckBox.
CheckBox checkBox = (CheckBox)grv_Test1.Rows[my_Data_From_Grid].Cells[2].Controls[0];
cbx_Test1_Active.Checked = checkBox.Checked;
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = ((CheckBox)e.Row.FindControl("WasAudited"));
if (chkSelect.Checked)
chkSelect.Enabled = false;
}
}

Extract a BoundField to a Label

I have a DetailsView which works fine using a data access layer and a query string. However, I'd like to extract one of the fields and use it as the text in a label to go above the DetailsView as a title to that page.
Is this possible? And if so, how?
This is an abstract of the DetailsView:
<Fields>
<asp:BoundField DataField="bandname" HeaderText="Band" />
<asp:BoundField DataField="contactname" HeaderText="Contact" />
<asp:BoundField DataField="county" HeaderText="County" />
</Fields>
and the code behind:
if (Request.QueryString.Count != 0)
{
int id = int.Parse(Request.QueryString["bandid"]);
dtvBand.Visible = true;
List<Band> bandDetails = new List<Band> { BandDAL.AnonGetAllBandDetails(id) };
dtvBand.DataSource = bandDetails;
dtvBand.DataBind();
}
What I'd like to do is take the data in the first BoundField row and make it the text of a label. Pseudocode:
Label1.Text = (<asp:BoundField DataField="band")
I would not try to find the text on the DetailsView but in it's DataSource. You could use the DataBound event which is triggered after the DetailsView was databound, so it's ensured that the DataItem exists.
It depends on the Datasource of your DetailsView. Often it is a DataRowView. You have to cast it, then you can access it's column:
protected void DetailsView1_DataBound(Object sender, EventArgs e)
{
DetailsView dv = (DetailsView)sender;
string yourText = (string)((DataRowView)dv.DataItem)["ColumnName"];
Label1.Text = yourText;
}
If it's not a DataRowView use the debugger to see what dv.DataItem actually is.
I managed to achieve what I wanted using:
string titletext = dtvBand.Rows[0].Cells[1].Text.ToString();
dtvBand.Rows[0].Visible = false;
lblBand.Text = titletext;
It takes the first row of the DetailsView, puts it above the rest in a Label so it can be formatted as a header, then hides the first row of the DetailsView.
How about using a TemplateField as what Tim mentioned:
<Fields>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Band") %>' />
</ItemTemplate>
</asp:TemplateField>
</Fields>

DetailsView: How to set a HiddenField value using the CommandArgument on a New command?

I have inherited some code that has a GridView and a DetailsView in a webpart control.
The DetailsView is able to create two different kinds of an object e.g. TypeA and TypeB.
There's a dropdown list that filters the GridView by object type and the DetailsView has an automatically generated Insert button.
<asp:DetailsView ID="myDetailsView"
AutoGenerateInsertButton="True"
AutoGenerateEditButton="True"
AutoGenerateRows="false"
OnItemUpdating="OnItemUpdating"
DefaultMode="ReadOnly"
OnDataBound="OnDetailsViewBound"
OnItemInserting="OnItemInserting"
OnModeChanging="OnDetailsViewModeChanging"
runat="server">
I have been asked to:
remove the filter on the GridView; and
split the New buttons/links into two so there's a separate button for creating each type of object.
Removing the filter means that I need some other way to track what kind of object we're creating.
I have split the New links by changing the above to:
<asp:DetailsView ID="myDetailsView"
AutoGenerateInsertButton="False"
AutoGenerateEditButton="True"
AutoGenerateRows="false"
OnItemUpdating="OnItemUpdating"
DefaultMode="ReadOnly"
OnDataBound="OnDetailsViewBound"
OnItemInserting="OnItemInserting"
OnModeChanging="OnDetailsViewModeChanging"
runat="server">
and adding
<FooterTemplate>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkCreateNewTypeA" CommandName="New" CommandArgument="TypeA" CssClass="buttonlink">New Type A</asp:LinkButton>
<asp:LinkButton runat="server" ID="lnkCreateNewTypeB" CommandName="New" CommandArgument="TypeB" CssClass="buttonlink">New Type B</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</FooterTemplate>
I haven't yet removed the filter so the changes currently function the same as before, as I'm using the New command.
What I was hoping to be able to do is somehow capture the New event so I can put the CommandArgument value into a hidden field, that the DetailsView would then use to determine which type of object it's creating and also to show/hide fields.
When I put breakpoints in all of the event handlers in my code, the first one to break is OnDetailsViewModeChanging, which doesn't have access to the CommandArgument.
OnItemCommand (if it's hooked up) is triggered when any button within the DetailsView is pressed and does give me access to the CommandArgument but I'm not sure what exactly needs to be done within this method to mimic the chain of events that occurs when you use automatically generated buttons.
Is my only option for retrieving the CommandArgument to capture it in the OnItemCommand event handler or is there some other event that is triggered on the New command?
Can anyone explain to me the sequence of events that occurs when the New command is triggered?
I read somewhere that it changes the mode to Insert but I don't know what else it does. I believe the OnItemInserting method isn't called until the "Insert" link is clicked.
Any help would be gratefully received!!
Edit:
I have found this link on DetailsView events but it hasn't answered my question.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview_events.aspx
Edit:
I have tried adding the following:
in ascx:
<asp:DetailsView ID="myDetailsView"
...
OnItemCommand="OnItemCommand"
...
runat="server">
...
<asp:TemplateField HeaderText="Object Type" HeaderStyle-CssClass="columnHeader">
<ItemTemplate>
<asp:HiddenField runat="server" ID="hidObjectType" Value=""/>
<asp:Label runat="server" ID="lblObjectType"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
in code behind:
protected void OnItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName.Equals("New"))
{
var objectType = e.CommandArgument.ToString();
HiddenField typeHidden = this.myDetailsView.FindControl("hidObjectType") as HiddenField;
if (typeHidden != null)
{
typeHidden.Value = objectType;
}
Label typeLabel = this.myDetailsView.FindControl("lblObjectType") as Label;
if (typeLabel != null)
{
typeLabel.Text = objectType;
}
}
}
I found that I didn't need to set the mode (this.myDetailsView.ChangeMode(DetailsViewMode.Insert);) in this method, as the OnDetailsViewModeChanging event handler still triggered.
This finds the controls and sets the values on them correctly. If I check the values again in OnDetailsViewModeChanging, their values are still set but as part of the logic in this method, there is a call to
this.myDetailsView.DataBind()
which causes a postback and at this point, the values are lost. I tried adding
EnableViewState="True"
but this made no difference. I've reviewed the page lifecycle (http://spazzarama.files.wordpress.com/2009/02/aspnet_page-control-life-cycle.pdf) and thought that maybe this.EnsureChildControls() would help but it's also made no difference.
An alternative would be to store the value in the session but I'd rather not.
As far as I can tell there is no event for capturing the "New" command aside from OnItemCommand, which captures all commands. (NOTE: You will need to make sure that CausesValidation="False" is set on your LinkButton or the code won't break into OnItemCommand).
When stepping through the code, the following occurred:
After the linkbutton was pressed, OnItemCommand is triggered. CommandName = "New" and here I could retrieve the CommandArgument
Next OnModeChanging is triggered. e.NewMode = "Insert". From all examples I've seen, here you call ChangeMode on the DetailsView and then call Databind() on it
Next OnDataBound is triggered as a result of calling Databind()
I didn't find a way to retain the value of the hidden variable between the various events so I ended up using a session variable. Code is below in case anyone wants it.
DetailsView declaration in the ASCX:
<asp:DetailsView ID="myDetailsView"
AutoGenerateInsertButton="False"
AutoGenerateEditButton="True"
AutoGenerateRows="false"
OnItemInserting="OnItemInserting"
OnItemUpdating="OnItemUpdating"
OnItemCommand="OnItemCommand"
DefaultMode="ReadOnly"
OnDataBound="OnDetailsViewBound"
OnModeChanging="OnDetailsViewModeChanging"
runat="server">
In the code-behind:
constant declarations...
private const string SESSIONKEY_MYVALUE = "MyValue";
private const string DEFAULT_OBJECTTYPE = "TypeA";
OnItemCommand event handler...
protected void OnItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName.Equals("New", StringComparison.InvariantCultureIgnoreCase))
{
var objectType = e.CommandArgument.ToString();
HiddenField typeHidden = this.myDetailsView.FindControl("hidObjectType") as HiddenField;
if (typeHidden != null)
{
typeHidden.Value = objectType;
}
HttpContext.Current.Session[SESSIONKEY_MYVALUE] = objectType;
}
}
OnModeChanging event handler....
protected void OnDetailsViewModeChanging(Object sender, DetailsViewModeEventArgs e)
{
if (e.NewMode == DetailsViewMode.Insert)
{
this.myDetailsView.ChangeMode(DetailsViewMode.Insert);
this.myDetailsView.DataBind();
}
}
OnDataBound event handler...
protected void OnDetailsViewBound(object sender, EventArgs e)
{
if (this.myDetailsView.CurrentMode == DetailsViewMode.Insert)
{
var sessionVar = HttpContext.Current.Session[SESSIONKEY_MYVALUE];
var objectType = sessionVar == null ?
DEFAULT_OBJECTTYPE :
sessionVar.ToString();
var typeHidden = this.myDetailsView.FindControl("hidObjectType") as HiddenField;
if (typeHidden != null)
{
typeHidden.Value = objectType;
}
}
}

GridView Checkbox Columns vs. Events

I have created a gridview with a column of checkboxes. I want the user to select the checkboxes, click the register button (outside the gridview), and have a title from the selected row displayed. From what I've read I should put the checkbox check in the button click event. I have done so, but apparently the only time it enters that event is at page load and right before the page loads, all the selected checkboxes are wiped. Therefore, my check for a selected checkbox never comes out true. Is there an event that would a better time to run this check, or perhaps a way to hold these values through the page load? The following isn't all my code, just the affected portions.
protected void regButton_Click(Object sender, EventArgs e)
{
StringBuilder regClasses = new StringBuilder();
for (int i = 0; i < SQLQueryClassListings.Rows.Count; i++)
{
//Response.Write(SQLQueryClassListings.Rows[i].Cells[0].Text + " checkbox check ");
GridViewRow checkRow = SQLQueryClassListings.Rows[i];
bool reg = ((CheckBox)(checkRow.FindControl("RowCheckBox"))).Checked;
if (reg)
{
regClasses.Append(SQLQueryClassListings.Rows[i].Cells[0].Text + " ");
}
}
Response.Write(regClasses);
}
<asp:GridView ID="SQLQueryClassListings" AutoGenerateColumns="false" runat="server"
BorderWidth="1px" BackColor="White" CellPadding="5" BorderColor="Black" RowStyle-BorderColor = "Black"
HeaderStyle-BackColor="#0D69F2" HeaderStyle-ForeColor="White" AlternatingRowStyle-BackColor="#E8E8E8" HeaderStyle-BorderColor="Black" GridLines="Both">
<Columns>
<asp:BoundField HeaderText="Classes" DataField="LeafName" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="250"
ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:BoundField HeaderText="Teacher" DataField="TeacherName" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="200"
ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:BoundField HeaderText="Available" DataField="SemesterEnds" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign ="Center" ItemStyle-Width="150" ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:HyperLinkField HeaderText="Course Description & Career Tracks" DataNavigateUrlFields="ApplicableTracks"
Text="See Description" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign ="Center" ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:TemplateField HeaderText="Register" HeaderStyle-BorderColor="Black" ItemStyle-BorderColor = "#ADADAD" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox runat="server" ID="RowCheckBox"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p>
<asp:Button ID="Button1" runat="server" Text="Register" OnClientClick="return confirm('You have sucessfully registered!')"
OnClick="regButton_Click" />
You need to get on the ItemDataBound event of the GridView control, find the CheckBox by ID, and do whatever you need.
It's hard to know for sure without seeing more of your code, but it sounds like your page is re-binding the GridView on postbacks (such as your regButton_Click event). So it rebuilds the GridView every time the page loads - even after your user clicks the register button.
If that is the case, you can fix this by changing the code you use to bind your GridView like this:
if (!this.IsPostback) {
SQLQueryClassListings.DataBind();
}
(This presumes that you have ViewState enabled for the page (or at least the GridView). There are other mechanisms you can use to communicate the client's state (such as checkbox selections) to the server, but ViewState (for all its faults) is the default tool for doign so in ASP.NET.)
A consequence is that the data shown in the GridView won't be completely up-to-date, but if you can tolerate that, this is a simple way to accomplish what you want.
You must read the checkboxes from the GridView.
So this code will bring back the IDs of the rows checked. It will give you the idea and then you can change it for what you need.
protected string getCheckedIds(GridView gv)
{
StringBuilder sb = new StringBuilder();
foreach (GridViewRow gvr in gv.Rows)
{
if (!gvrIsChecked(gvr)) // see below for this method
continue;
if (sb.Length > 0)
sb.Append(",");
sb.Append(gv.DataKeys[gvr.DataItemIndex].Value);
}
return sb.ToString();
}
protected bool gvrIsChecked(GridViewRow gvr)
{
// The location of your checkbox may be different.
object cb = gvr.Cells[0].Controls[gvr.Cells[0].Controls.Count - 2];
if (cb.GetType() != typeof(CheckBox))
return false;
if (!((CheckBox)cb).Checked)
return false;
return true;
}

GridView FindControl returns null when HeaderText is set

I have a GridView...
<asp:GridView EnableViewState="true"
ID="grdResults"
runat="server"
CssClass="resultsGrid"
OnRowDataBound="grdResults_OnRowDataBound"
AutoGenerateColumns="false"
HeaderStyle-CssClass="header"
OnRowCommand="grdResults_OnRowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblView"
runat="server"
Visible="false"
Text="View">
</asp:Label>
<asp:HyperLink ID="hypEdit"
runat="server"
Visible="false"
Text="(Edit)"
CssClass="edit">
</asp:HyperLink>
<asp:LinkButton ID="btnDelete"
runat="server"
Visible="false"
Text="(Delete)"
CssClass="delete"
CommandName="DeleteItem"
OnClientClick="return confirm('Are you sure you want to delete?')">
</asp:LinkButton>
<asp:HyperLink ID="hypSelect"
runat="server"
Visible="false"
Text="(Select)"
CssClass="select">
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This has one static column containing a label two hyperlinks and a link button and also has a number of dynamically generated columns...
private void SetupColumnStructure(IEnumerable<string> columnNames)
{
var columnNumber = 0;
foreach (var columnName in columnNames)
{
var templateColumn = new TemplateField
{
ItemTemplate = new CellTemplate(columnName)
};
grdResults.Columns.Insert(columnNumber, templateColumn);
columnNumber++;
}
}
As part of the OnRowDataBound handler I retrieve one of the controls in the statically column and set some attributes on it...
protected void grdResults_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
.
.
.
var row = e.Row;
var rowData = row.DataItem as Dictionary<string, object>;
if (rowData != null)
{
if ((bool)rowData[displayEditLink])
{
var hypEdit = (HyperLink)row.FindControl("hypEdit");
hypEdit.NavigateUrl = "~/Pages/Edit.aspx?action=Edit&objectType=" + rowData[objectTypeLiteral] + "&id=" + rowData[objectIdLiteral];
hypEdit.Visible = true;
}
}
.
.
.
}
This all works fine but no column names are displayed. So I then modify the SetupColumnStructure method so that the HeaderText is set on the template field like this...
private void SetupColumnStructure(IEnumerable<string> columnNames)
{
var columnNumber = 0;
foreach (var columnName in columnNames)
{
var templateColumn = new TemplateField
{
ItemTemplate = new CellTemplate(columnName),
HeaderText = columnName
};
grdResults.Columns.Insert(columnNumber, templateColumn);
columnNumber++;
}
}
For some reason this one extra line change causes the row.FindControl("hypEdit"); call in the OnRowDataBound handler to return null.Can anyone see something im missing here or has anyone experienced a similar issue?
UPDATE
I've made sure that I'm not referring to a header or footer row here. Also, if I step over the object reference exception this occurs for every item that is in the DataSource.
Not sure if this helps, but as I expected, when I stepped through the code the table has generated all the columns expected but all cells (DataControlFieldCells) contain no controls when the HeaderText is set, yet all expected controls when it isnt set.
All very strange. Let me know if you can spot anything else.
When you added the HeaderText, a new RowType was added to the gridview. You'll need to check what type of row raised the OnRowDataBound event and take the appropriate action. In your case, just checking if the e.Row.RowType is a DataRow should solve your problem:
protected void grdResults_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
if ((bool)rowData[displayEditLink])
{
var hypEdit = (HyperLink)row.FindControl("hypEdit");
hypEdit.NavigateUrl = "~/Pages/Edit.aspx?action=Edit&objectType=" + rowData[objectTypeLiteral] + "&id=" + rowData[objectIdLiteral];
hypEdit.Visible = true;
}
}
}
Its because the control you are searching for is contained within another control. FindControl() does not look inside control collections of controls. You will need to write a recursiveFindControl() method.
Hope this helps a little!

Resources