When my datagrid is in edit mode, one of my columns is edited using a drop
down list.
I'm able to bind the DropDownList to a DataSource when in edit mode.
HOWEVER, I can't preset the DropDownList's value when the Edit button is
clicked for that row inside the datagrid.
Here's a simplified version of my datagrid:
<asp:datagrid id="dgHPU" runat="server"
OnEditCommand=" dgHPU_OnEditCom mand"
OnUpdateCommand ="dgHPU_OnUpdat eCommand"
OnCancelCommand ="dgHPU_OnCance lCommand"
OnItemDataBound ="dgHPU_OnItemD ataBound">
<Columns>
<asp:BoundColum n DataField="HPUI d" Visible="False" ReadOnly="True"/>
<asp:EditComman dColumn ButtonType="Lin kButton" UpdateText="Sav e"
CancelText="Can cel" EditText="Edit" ItemStyle-Width="10%"/>
<asp:TemplateCo lumn HeaderText="Hou r">
<ItemTemplate >
<asp:label id="lblHourPeri od" runat="server" Text='<%#
DataBinder.Eval (Container, "DataItem.HourP eriod") %>'/>
</ItemTemplate>
<EditItemTempla te>
<asp:DropDownLi st ID="cboEditHour Period" Runat="server"
DataSource='<%#
FetchHourPeriod sUpdate((DataBi nder.Eval(Conta iner,
"DataItem.HPUId ")).ToStrin g()) %>'
DataTextField=" HourPeriod" DataValueField= "HourPeriod_Unf "/>
</EditItemTemplat e>
</asp:TemplateCol umn>
</asp:datagrid>
I figured that I should preset the DropDownList in the ItemDataBound event
of the datagrid, so I did this:
protected virtual void dgHPU_OnItemDat aBound(object source,
System.Web.UI.W ebControls.Data GridItemEventAr gs e)
{
if (e.Item.ItemTyp e == ListItemType.Ed itItem)
{
Label lblHourPeriod = ((Label)
e.Item.Cells[2].FindControl("l blHourPeriod")) ;
DropDownList cboEditHourPeri od = ((DropDownList)
e.Item.Cells[2].FindControl("c boEditHourPerio d"));
cboEditHourPeri od.SelectedInde x =
cboEditHourPeri od.Items.IndexO f(cboEditHourPe riod.Items.Find ByText(lblHourP e
riod.Text));
}
}
However, the FindControl call returns nothing, so then I obviously get an
Object reference not set to an instance of an object. error when I try to
set the SelectedIndex.
Anything I'm missing?