Reputation: 653
Hello everybody and thanks in advance,
Well, I have a DetailsView in my .aspx file and I can't access to a CheckBoxList control placed in the DetailsView's edit template. I've read a lot of threads about this but still can't find a solution. Here's the code...
<asp:DetailsView ID="MyDetailsView" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataSourceID="DataMyDetailsView">
...
...
<asp:TemplateField HeaderText="DATA" SortExpression="DATA">
<EditItemTemplate>
<div style="width:400px; height:300px; overflow-y:auto">
<asp:CheckBoxList ID="DataCL" runat="server" DataSourceID="DataEDIT" DataTextField="DATA" DataValueField="ID_DATA">
</asp:CheckBoxList>
</div>
Then, in my .cs file I have this piece of code...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Do something
}
else
{
CheckItems();
}
}
...
...
public void CheckItems()
{
CheckBoxList DataCL = (CheckBoxList)MyDetailsView.FindControl("DataCL");
using (conexion)
{
conexion.Open();
cmd.Connection = conexion;
DataSet ds = new DataSet();
string cmdstr = "SELECT * FROM DATA";
SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conexion);
adp.Fill(ds);
DataCL.DataSource = ds;
DataCL.DataTextField = "DATA";
DataCL.DataValueField = "ID_DATA";
DataCL.DataBind();
The problem is that when the execution reaches the first line in which the control is called (DataCL.DataSource = ds;), a "NullPointerExeception" is thrown, however I can access easily to controls in ItemTemplate.
Please, can someone help me in this. Thanks again!
Upvotes: 0
Views: 384
Reputation: 17600
You can't do this, because this control is dynamically created after data binding. Instead attach your grid to DataBound
(MSDN) event and bind checked box list there
protected void MyDetailsView_DataBound(object sender, EventArgs e)
{
if (MyDetailsView.CurrentMode == DetailsViewMode.Edit)
{
CheckBoxList DataCL = (CheckBoxList)MyDetailsView.FindControl("DataCL");
using (conexion)
{
// your data bound code goes here
}
}
}
Upvotes: 2