ASP.NET data bind two-way, bi-directional from code behind

so for two-way (bi-directional) databinding in ASP, we do this…

<asp:textbox id="txtField" runat="server" 
    text='<%# Bind("SomeField") %>'>
</asp:textbox>

SomeField is located on the DataSource of the DetailsView that serves as the container for the textbox.

Alternatively I could do this from code-behind (using the textbox’s OnDataBinding event):

protected void SomeField_OnDataBinding(object sender, EventArgs e)
{ 
  ((TextBox)sender).Text = Eval("SomeField").ToString();
}

However, EVAL is read-only…how can I specify Bind (two-way) from code-behind?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I’ve managed to find a work-around for my “edge-case”.

I am using LLBLGen subtypes and therefore need to switch the datasource of the detailsview based on a radiobutton filter selected by the user.

I tried to bind to the sub type field “declaratively” in ASP using <%# Bind(…
This did not work.

I had to resolve to a code-behind “hack” where I conditionally display the controls in the detailsview using details_view pre-render method.

For each field I then conditionally setup it’s one-way (read-only) bind in OnDataBinding…

e.g. ((TextBox)sender).Text = Eval("FilePrefix").ToString();

Finaly to get the data to push into the datasource, I hack the DetailsView OnItemInserting/Updating events (conditionally as well)…

e.Values["FilePrefix"] = txtFilePrefix.Text;

I feel so dirty after this hack I think I need a shower…

I still hope someone can provide a cleaner approach 🙂

Method 2

Did you check out this page on MSDN, Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control ?


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x