In order to populate any server control with data dynamically, is it
ALWAYS NECESSARY to either BIND the DataSource to that server control
or call the DataBind method of that server control?
For e.g. consider the following code:
<script runat="server">
Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
If Not (Page.IsPostBack) Then
'create an array of colors
Dim arrColors() As String = {"red", "blue", "green",
"yellow"}
lbColors.DataSource = arrColors
lbColors.SelectedIndex = 0
End If
lblMessage.DataBind()
End Sub
</script>
<form runat="server">
<asp:ListBox id="lbColors" AutoPostBack="true" SelectionMode="single"
runat="server"/>
<asp:Label id="lblMessage" Text=<%# lbColors.SelectedItem.Text %>
runat="server"/>
</form>
The above code generates the following error:
Object reference not set to an instance of an object.
the offending line being
<asp:Label id="lblMessage" Text=<%# lbColors.SelectedItem.Text %>
runat="server"/>
Is the error thrown because the ListBox named "lbColors" HASN'T been
BOUND to the DataSource?
On the other hand, if the line
lblMessage.DataBind()
is replaced with
lbColors.DataBind()
then the ListBox would get populated with the 4 colors but the Label
named "lblMessage" won't generate any text when the page loads for the
first time or when an item is selected in the ListBox. Is it because
DataBinding Expressions are evaluated only when the DataBind method of
the control is called & since the DataBind method of the Label control
isn't being called anywhere in the code, the DataBinding Expression of
the Label control doesn't get evaluated & hence the Label doesn't
generate any output?
Please correct me if I am wrong.
Thanks,
Arpan