Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert all controls on an aspx webform to a read-only equivalent

Tags:

Has anyone ever written a function that can convert all of the controls on an aspx page into a read only version? For example, if UserDetails.aspx is used to edit and save a users information, if someone with inappropriate permissions enter the page, I would like to render it as read-only. So, most controls would be converted to labels, loaded with the corresponding data from the editable original control.

I think it would likely be a fairly simple routine, ie:

Dim ctlParent As Control = Me.txtTest.Parent  
Dim ctlOLD As TextBox = Me.txtTest  
Dim ctlNEW As Label = New Label  
ctlNEW.Width = ctlOLD.Width  
ctlNEW.Text = ctlOLD.Text  
ctlParent.Controls.Remove(ctlOLD)  
ctlParent.Controls.Add(ctlNEW)  

...is really all you need for a textbox --> label conversion, but I was hoping someone might know of an existing function out there as there are likely a few pitfalls here and there with certain controls and situations.

Update:
- Just setting the ReadOnly property to true is not a viable solution, as it looks dumb having things greyed out like that. - Avoiding manually creating a secondary view is the entire point of this, so using an ingenious way to display a read only version of the user interface that was built by hand using labels is wat I am trying to avoid.

Thanks!!

like image 545
tbone Avatar asked Sep 16 '08 22:09

tbone


2 Answers

Scott Mitchell posted a good article on this a while back.

https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx

I've used this approach in the past in conjection with css on the 'read only' fields to make them look and work exactly like a label, even though they are in fact text boxes.

like image 109
Keith Patton Avatar answered Sep 30 '22 14:09

Keith Patton


You could use a multiview and just have a display view and an edit view.. then do your assignments as:

lblWhatever.Text = txtWhatever.Text = whateverOriginatingSource;
lblSomethingElse.Text = txtSomethingElse.Text = somethingElseOriginatingSource;

myViews.SelectedIndex = myConditionOrVariableThatDeterminesEditable ? 0 : 1;

then swap the views based on permissions.

not the most elegant but will probably work for your situation.

Maybe I should elaborate a little.. dismiss the psuedo (not sure if I have the selectedindex yada yada right.. but you get the point).

<asp:Multiview ID="myViews" SelectedIndex="1">
    <asp:View ID="EditView">
        <asp:TextBox ID="txtWhatever" /><br />
        <asp:TextBox ID="txtSomethingElse" />
    </asp:View>
    <asp:View ID="DisplayView">
        <asp:Label ID="lblWhatever" /><br />
        <asp:Label ID="lblSomethingElse" />
    </asp:View>
</asp:Multiview>
like image 20
Quintin Robinson Avatar answered Sep 30 '22 15:09

Quintin Robinson