0

I have following code in gridview:

 <% If Eval("LabelType").ToString() = "Singleline" Then%>  <asp:TextBox ID="txtSingleLine" runat="server" ></asp:TextBox> <% End If%>
 <% If Eval("LabelType").ToString() = "Multiline" Then%>  <asp:TextBox ID="txtMultiline" runat="server"  TextMode="MultiLine" ></asp:TextBox> <% End If%>                                            
  <% If Eval("LabelType").ToString() = "Image" Then%>  <asp:FileUpload ID="FileUpload1" runat="server" /> <% End If%>

I am getting following error:

Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control

From this question i came to know that # should be added, but when i added as:

It was not accepting this (showing blue line below whole statement).

Please tell me where i am making mistake.

Please help me.

I am using vb.net but answer in c# is also helpful.

Community
  • 1
  • 1
C Sharper
  • 8,284
  • 26
  • 88
  • 151

2 Answers2

1

You could try setting the visibility on each control based on the value of LabelType like so:

<asp:TextBox ID="txtSingleLine" runat="server" Visible="<%# Eval("LabelType").ToString() == "Singleline" %>"></asp:TextBox>
<asp:TextBox ID="txtMultiline" runat="server"  TextMode="MultiLine"  Visible="<%# Eval("LabelType").ToString() == "Multiline" %>" ></asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server"  Visible="<%# Eval("LabelType").ToString() == "Image" %>" />
Riv
  • 1,849
  • 1
  • 16
  • 16
1

Like the error says you cannot have an Eval outside of data bound control, so I would recommend that you dynamically insert the controls into a PlaceHolder control, like this:

Markup:

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

Code-behind:

If LabelType = "Singleline" Then
    ' Create textbox and add to placeholder
    Dim textbox = New TextBox()
    textbox.ID = "txtSingleLine"
    PlaceHolder1.Controls.Add(textbox)
Else If LabelType = "Multiline" Then
    ' Create textbox with multi-line text mode and add to placeholder
    Dim multilinetextbox = New TextBox()
    multilinetextbox.ID = "txtMultiline"
    PlaceHolder1.Controls.Add(multilinetextbox)
Else If LabelType = "Image" Then
    ' Create file upload and add to placeholder
    Dim fileupload = New FileUpload()
    fileupload.ID = "FileUpload1"
    PlaceHolder1.Controls.Add(fileupload)
End If

Note: LabelType in the code above is the string representation of what you were doing in Eval("LabelType").ToString().

Karl Anderson
  • 34,606
  • 12
  • 65
  • 80