Passing dynamic variable to UserControl attribute - asp.net

I'm creating an UserControl and I'm passing a variable to it.
It works fine if I do it this way:
<uc:TestControl ID="testControl" runat="server" Variable="test"></uc:TestControl>
However I want to pass a dynamic variable to the control like this:
<uc:TestControl ID="testControl" runat="server" Variable="<%=dynamicVariable%>"></uc:TestControl>
But unfortunately that doesn't work and I know I could assign it on Page_Load but I don't like that way.
So I'm wondering if it's possible at all. Is there any way to assign a dynamic variable to an attribute like I wanted above? Or am I required to do it in Page_Load?
Any feedback would be appreciated!
Thanks!

<%= syntax doesn't work with controls marked as runat="server" .Try using the databind syntax
Variable="<%#dynamicVariable%>"
Then calling databind on the user control as per this SO question
EDIT
To database i think it's a straight
testControl.DataBind()
supported in ASP.Net 3.5 and greater.

Related

Data binding simple variable not working

This is the page code for the control:
<asp:TextBox id="someID" maxlength="10" columns="10" runat="server" Text="<%# work %>" />
This is how I set up and populate the variable before page is rendered, it is in the code behind, I have tried I think all the variations available for the variable declaration, e.g. public, shared, protected, etc.:
Public work As String
work = "987654321"
The textbox always comes up blank. referred to this ms kb page for how this work and it has a specific example.
However, it didn't explain anywhere if there is some special way of declaring the variables used in the binding or some special way to set the value of the variable, or is there something needed to allow the <%# syntax to work?
Binding doesn't happen automatically. You have to call DataBind() either from Page control or the text control. Try put it in Page_Load() method.

vb asp.net : A way to avoid repeating a code in common in ItemTemplate and EditItemTemplate

I'm a newbie in asp.net.
When using FormView, there is a big amount of code in ItemTemplate, EditItemTemplate and InsertItemTemplate which is almost identical.
For example:
<asp:ListBox ID="ListBox2" runat="server" Rows="1" CssClass="field"
DataSourceID="StatusList" DataTextField="DESCRIPTION"
DataValueField="STAT_ID" SelectedValue='<%# Bind("STAT_ID") %>'>
</asp:ListBox>
(Note: at the exception that Eval() would be used instead of Bind() in ItemTemplate)
I've been trying to avoid repeating this code but without the expecting result:
ListView allows the use of LayoutTemplate - but I didn't see any examples that insert this kind of code in LayoutTemplate. And inserting this code in LayoutTemplate would result in an error.
DetailView allows to produce code automatically but I'd like to use a specific design (for ex. using "fieldset" that encompasses some fields).
What would be the best way to avoid repeating this kind of code ?
You don't have to much choice about seperately specifying the Bind/Eval part, but you do have some control over the other pieces. You can make a custom UserControl that contains your layout.
Usually I include a property on this usercontrol called "Mode" which I either set to Edit or View, then based off of this property I change enabled/visible properties on the controls. You'll also need to include a property for each value you want bound/displayed in the usercontrol.
Put some labels, textboxes, etc... in your designer and hook them up to properties in your code behind, put the usercontrol on your page in your item/edit template and eval/bind to your data to the various properties (make sure to set the mode so it displays right).

ASP.NET databinding / getting variables from codebehind

So I haven't used ASP.NET for three years or so and I'm really rusty on it. My old code isn't available to me for review (at an old company). This question should be pretty basic, but I can't find any good or reliable or not-super-old resources on the issue, so I'm asking here.
Can I get a general overview of databinding again? I remember it being really useful for select boxes, etc., but I don't really remember how it works. Maybe a good ASP.NET tutorial in general, because I don't remember how it handles POST requests or anything like that really either. Should I just try ASP.NET MVC?
Relatedly, suppose I have a public variable in my codebehind page. Right now I am accessing it by saying Page.DataBind() at the end of the page load function and then running <%# variable %> in the ASPX, but that's not how I remember doing it before and I reckon that it's not very good practice. What's the best way to display variables from codebehind?
Databinding in general (at least in the WebForms model) is mostly a case of assigning fields to be displayed, setting the DataSource property to a suitable object that contains those fields e.g. a DataReader, DataTable, a Collection, and calling the DataBind method. So for your select case, you'd put an <asp:dropdownlist runat="server" id="MyDropDownList"> in the markup for the page, and then in the code
DataSet myDataSet;
myDataSet = someDataMethod();
MyDropDownList.DataTextField = fieldname;
MyDropDownList.DataValueField = fieldname;
MyDropDownList.DataSource = myDataSet;
MyDropDownList.DataBind();
Or you can avoid writing that kind of code and do it in the markup if you use a DataSource control e.g. <asp:SqlDataSource>, <asp:ObjectDataSource>
<asp:SqlDataSource runat="server" id="MySqlDataSource" ConnectionString="aConnectionString" SelectCommand="MyStoredProcName" SelectCommandType="StoredProcedure" />
<asp:dropdownlist runat="server" id="MyDropDownList" DataSourceId="MySqlDataSource" DataTextField="fieldname" DataValueField="fieldname">
For putting your variable on a page, the way you might have done it before is to have a label or textbox on the page, that in your code-behind you assign your variable to the Text property e.g.
<asp:label runat="server" id="MyLabel" />
MyLabel.Text = myVariable.ToString();
Postbacks: you can test the IsPostback property of a page in code-behind to determine if it's a postback or not. After the Page_Load method, other methods will fire if you've defined them e.g. SelectedIndexChanged for a DropDownList.
I really wanted to answer this question with examples and code etc.. but I would just be rehashing information that has been on the web for years and been explained in blogs and articles countless times. You can start with this article
which explains almost everything you need to know.
I have bolded the ones that I think are important to note that some my skim over.
<%# %> Syntax
Page.DataBind() versus Control.DataBind()
Data-bound list controls
Repeater control
DataList control
DataGrid control
Accessing data
DataSet class
DataReader class
Binding in list control templates
DataBinder.Eval method
Explicit casting
ItemDataBound event
As for learning MVC over webforms, that is whole different story. They both have pluses and minuses depending on your time, what you NEED to know and what portions of the project are important. Both techs can accomplish the same thing as they are all ASP.NET at their core, just different approaches so you will be fine either way.

CheckboxList - Use web.config value in text field

The scenario I'm dealing with is I have a set of entries in a database that have an image associated with them. This image needs to be 'accepted' or 'rejected' via a web interface.
I'm using ASP.NET WebForms.
I'm attempting to databind my recordset of entires to a CheckBoxList control. I would like to combine data from my dataset with information from the web.config file and plain text to display an image:
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataSourceID="DataSource1"
DataTextField="ImageIdentifier"
DataValueField="EntryId"
DataTextFormatString="<img src='<%$ AppSettings:GetImageUrl %>{0}' />" />
This approach correctly outputs the plain text and the DataTextField value, however it does not interpret the code inside the <% %> block and prints the whole thing literally in the generated HTML, in spite of it being correctly highlighted in the editor.
Is this possible to achieve declaratively? If not, is there a better way than iterating through the entries in the list in code on the OnDataBound event?
Thanks in advance,
Jamie
I believe you're using the wrong <% tag. In order to evaluate in a binding expression like that it should be <%#
What does your web.config look like? You'll won't be able to use that binding syntax here - you'll have to hook into the databound event of the checkbox and iterate each checkbox, updating them as necessary from the values in your web.config.
EDIT
If you don't want to iterate each checkbox after the checkboxlist has been databound, you'll have to update your dataset first, before you bind to it.

What other objects are accessible inside <%# %> tags in aspx?

I run into similar codes like this all the time in aspx pages:
<asp:CheckBox Runat="server" ID="myid" Checked='<%# DataBinder.Eval(Container.DataItem, "column").Equals(1) %>'>
I was wondering what other objects I have access to inside of that <%# %> tag. How come DataBinder.Eval() and Container.DataItem are not visible anywhere inside .CS code?
Within <%# %> tags you have access to
Anything that is visible in your code-behind class (including protected methods and properties).
Anything declared on the aspx page using <#import #>.
Anything passed in as the event arguments when the ItemDataBound event is fired (e.g. RepeaterItemEventArgs, DataListItemEventArgs, etc).
Container is actually a wrapper for RepeaterItemEventArgs.Item, DataListItemEventArgs.Item, etc. So you can actually access it in code behind within your ItemDataBound events as e.Item (e normally being the event arguments parameter name).
DataBinder is also accessible in code behind by using System.Web.UI.DataBinder.
On a side note, casting the Container.DataItem is preferred over using Eval. Eval uses reflection so there's an overhead there. In VB.NET it would be something like
<%#DirectCast(Container.DataItem, DataRow)("some_column")%>
Or C#
<%#((DataRow)Container.DataItem)["some_column"].ToString()%>
I believe you have access to anything within scope of the page class, though the results of the expression are converted to a string, so you can't embed conditional expressions the way you can with "<%" expression holes.
Here is a nice blog post which dives under the covers of the generated ASPX class.
Hope this helps.
<%# is specific to inline ASPX databinding like the link ckramer posted suggests.
How come DataBinder.Eval() and Container.DataItem are not visible anywhere inside .CS code?
To access the binding item in codebehind you would need to set up an ItemDataBound event.
ASP.NET generates a subclass of TemplateControl for each occurence of a template. Databinding statements are expressions used in a method inside that class. Thus, you can call any public/protected instance method on TemplateControl. See any example that uses XPath, as those will use the XPath and XPathSelect methods; Eval, XPath and XPathSelect are all instance methods on TemplateControl.
DataBinder is actually a separate class, and Eval is a public static method on it; it's in System.Web.UI. DataBinder.Eval and plain Eval are not directly related though they do very similar things visibly.
I believe that "Container" is actually a local variable or parameter where databinding statements are compiled. I can't remember its type at the moment.
using <%# %> actually means that code inside this block will execute when page.DataBind() method is being executed. Thus you can access anything at that point accessible as protected/public to that particular page/control.
Great example
<%#((System.Data.DataRow)Container.DataItem)["ColumnName"].ToString()%>

Resources