Databinding to text boxes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anusha007khader
    New Member
    • Apr 2010
    • 2

    #1

    Databinding to text boxes

    I have no idea about how to bind data to text box.

    I have a user details aspx form and i wnt to display the data entered by the user before to be displayed in the text box when user clicking the Edit profile button.

    i.e the values from sql database should be bounded with the text boxes. There are more than 27 text boxes in the user profile form.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    I'm not sure where to start.
    Could you please post what you have tried so far to solve the problem so that we have something to help you with?

    Thanks

    -Frinny

    Comment

    • tlhintoq
      Recognized Expert Specialist
      • Mar 2008
      • 3532

      #3
      Original Poster: I don't know how to use a search engine. Could someone do it for me?
      Let Me Google That For You (LMGTFY): for all those people who find it more convenient to bother you with their question rather than search it for themselves.

      Comment

      • anusha007khader
        New Member
        • Apr 2010
        • 2

        #4
        Originally posted by Frinavale
        I'm not sure where to start.
        Could you please post what you have tried so far to solve the problem so that we have something to help you with?

        Thanks

        -Frinny
        Thanks Frinny for your response


        In short i just want to bind some data with the text boxes in my aspx form. But the data which i need to bind with the text boxes is from my sql database .

        Hope tht its clear to u, there are 27 text boxes in my page.

        Waiting for your help...

        Comment

        • Frinavale
          Recognized Expert Expert
          • Oct 2006
          • 9749

          #5
          I'm still not sure where to start helping you.
          If I were you I'd create a class used to represent your user.
          I would retrieve the user's details from the database.
          I would use reflection to loop through the properties of the user class to create textboxes used to display and gather the user information.

          -Frinny

          Comment

          • DaveRook
            New Member
            • Jul 2007
            • 147

            #6
            At a guess

            <asp:Textbox ID="id" runat="server" text='<%#Eval(" DatabaseColumnN ame") %>' /> (note single quotes)

            This assumes you've used set up a dataset

            Dave

            Comment

            • Frinavale
              Recognized Expert Expert
              • Oct 2006
              • 9749

              #7
              See that's the thing...maybe I'm just lazy or something but dragging 27 TextBoxes onto the page and naming them all and then binding to them...

              Seems like too much work.


              It'd be easier to create a ListOf TextBoxes...
              Use Reflection to loop through all of the User's properties.
              Each property you find create a TextBox (setting the TextBox's ID = the property name so that you can reference it later). Add the newly created TextBox to the ListOf TextBoxes and to a control (like a panel) that will contain the user's information. (Do all of this in your Page Init Event).

              Then in your page load event, the first time the page is loaded...call a method on your user class to "get" the user's information. This will populate the class with data....

              Now typically I just use reflection again at this point to populate the TextBoxes with text....but I see no reason why you can't set up the binding to the properties when you're dynamically creating the TextBoxes. (I've never tried this, so it might be harder than I think...)

              See there's the other thing (lazieness coming out again) but I've created a "Field" user control that has a Textbox and a "Prompt" (a label control) used for describing the what the TextBox represents. I dynamically add these user controls to the page instead of just TextBoxes (since it makes more sense).

              Like I said I'm a little lazy and don't like it when some-thing that I need to display/retrieve data for has 100+ fields that I need to interact with...it's just easier to reflect than do this manually.

              -Frinny

              Comment

              • DaveRook
                New Member
                • Jul 2007
                • 147

                #8
                Frinny

                I don't think you appreciate how valuable posts like yours are! Thank you. By doing so, you're giving people (including myself) an insight into best practices, how to approach problems etc.

                Thank you

                Dave

                Comment

                • Frinavale
                  Recognized Expert Expert
                  • Oct 2006
                  • 9749

                  #9
                  I'm not sure it's best-practices but over time I've found my programming style is changing to be a lot more abstract...work ing at a level where I don't care what the property names are when displaying/retrieving data from the user.


                  Normally I don't just give out my thoughts on the problems that I'm helping with because I've learned that my approach to solving problems is vastly different than the people asking about the problem. I find it's easier to get insight into how the user thinks to give them a solution that they can easily understand and is their style of programming.

                  Here is a snippet of what I was talking about earlier...the code is clean, and simple and easy to use/maintain.

                  I have a Web User Control that has a Label to display a prompt/text and a TextBox that is used to display and gather data. This control is called "FieldUserContr ol" for simplicity and has 2 important properties: the Text property (which gets and sets the TextBox.Text property) and the Prompt property (which gets and sets the Label.Text property). It has other properties for styling etc but we won't get into them because I want to keep my point clear.

                  Now say we have a page (or user control) and we want to let the user see/edit a bunch of Text Properties of a class "XYZ".

                  First of all I would declare a ListOf FieldUserContro ls (at Page level scope), used as a container for all the FieldUserContro ls required to let the user see/edit the XYZ's properties.

                  Then in the Page Init Event I would use Reflection (so you need to import the namespace) to rip through the all the Properties in XYZ, create a FieldUserContro l for each one, give the FieldUserContro l the ID that matches the property name, and add the FieldUserContro l to the page and to the ListOf FieldUserContro ls:

                  Code:
                  Imports System.Reflection
                  '......
                  Private _xyzFields As List(Of FieldUserControl) 'a container for all the FieldUserControls required to display/retrieve data for XYZ
                  Private urlToFieldControl As String = "~/FieldUserControl.ascx" 'Path to the FieldUserControl
                  
                  Private Sub MyPage_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
                    _xyzFields= New List(Of FieldUserControl)
                    InstantiateXyzFields()
                  End Sub
                  
                  Private Sub InstantiateXyzFields() 
                    'Grabbing all of the properties for class XYZ
                    Dim xyzFieldProperties() As PropertyInfo = GetType(XYZ).GetProperties
                  
                    'Ripping through each XYZ property
                    For i As Integer = 0 To xyzFieldProperties.Length - 1
                      'Creating a FieldUserControl control to represent the property
                      Dim f As FieldUserControl= CType(Page.LoadControl(_urlToFieldControl), FieldUserControl)
                      
                     'Getting the property information
                      Dim pi As PropertyInfo = xyzFieldProperties(i)
                  
                     'Setting the ID of the FieldUserControl to the property name
                      f.ID = pi.name
                    
                     'Setting the Prompt for the FieldUserControl to the property name
                      f.Prompt = pi.name
                  
                      'Adding the FieldUserControl control to a Panel that is on the page where we want
                      'the FieldUserControls to be displayed 
                      PanelThatContainsXYZsFields.Controls.Add(f)
                     
                      'Adding the field control to the list of fields for later use
                      _xyzFields.Add(f)
                    Next
                  End Sub
                  Now we have a FieldUserContro l control (a Label-TextBox pair) for every property that is part of the XYZ class added to the page....prompt is set with the name of the property so that the user can identify what it is (what's really nice is that you can set up resources that contain prompts in the languages that your application supports...usin g the property names as the Key value for each prompt...that way you can retrieve the translated text/user friendly prompt for each property easily)

                  At this time we have FieldUserContro ls added to the page with prompts but the TextBoxes don't contain any information. Say XYZ has a method called "Populate" that goes to the database, retrieves the information, and populates the class's properties with the data retrieved.

                  I would call this method in the Page Load event only if isPostback=fals e (the first time the page is loaded). Then I would loop through all of the properties for the class and set the corresponding FieldUserContro l's Text property:
                  Code:
                    
                  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
                    If IsPostBack = False Then
                      DisplayXYZData()    
                    End If
                  End Sub
                  
                  Private Sub DisplayXYZData()
                    'Creating an instance of the XYZ class
                    Dim instanceOfXYZ As New XYZ
                  
                    'Populating the instance of the class with data
                    instanceOfXYZ.Populate()
                  
                    'Grabbing all of the properties for class XYZ
                    Dim xyzFieldProperties() As PropertyInfo = GetType(XYZ).GetProperties
                  
                    'Ripping through each XYZ property
                    For i As Integer = 0 To xyzFieldProperties.Length - 1   
                     'Getting the property information
                      Dim pi As PropertyInfo = xyzFieldProperties(i)
                  
                      'Getting the property name & storing it into a string (for Lambda expression to work nicely)
                      Dim propertyName As String = pi.Name
                  
                      'Using the Array.Find method to retrieve the FieldUserControl that corresponds with the property
                      'Note that I'm using a Lambda expression for simplicity sake
                      Dim f As FieldUserControl = Array.Find(_xyzFields.ToArray, Function(x) String.Compare(x.ID,propertyName)=0)
                  
                      'Making sure that the Array.Find method worked...that f exists before trying to use it
                      If f IsNot Nothing Then
                        'Setting the FieldUserControl's Text property with the value of the property
                        'that is in the instanceOfXYZ object
                         f.Text = pi.GetValue(instanceOfXYZ,Nothing)
                      End If
                    Next
                  End Sub
                  Tada: done.
                  We are displaying all properties of a class (whether it be 1 or 1000) on the screen with a Label for each property and a TextBox for each property. The TextBoxes are displaying data for the properties....w hat more could you ask for?

                  Oh retrieveing data is just as simple: get all the properties for the class, get the corresponding FieldUserContro l for the property...use the property Info's SetValue method to set the class with the data in the TextBox.

                  Code:
                  Private Sub RetrieveXYZData()
                    'Creating an instance of the XYZ class
                    Dim instanceOfXYZ As New XYZ
                  
                    'Grabbing all of the properties for class XYZ
                    Dim xyzFieldProperties() As PropertyInfo = GetType(XYZ).GetProperties
                  
                    'Ripping through each XYZ property
                    For i As Integer = 0 To xyzFieldProperties.Length - 1   
                     'Getting the property information
                      Dim pi As PropertyInfo = xyzFieldProperties(i)
                  
                      'Getting the property name & storing it into a string (for Lambda expression to work nicely)
                      Dim propertyName As String = pi.Name
                  
                      'Using the Array.Find method to retrieve the FieldUserControl that corresponds with the property
                      'Note that I'm using a Lambda expression for simplicity sake
                      Dim f As FieldUserControl = Array.Find(_xyzFields.ToArray, Function(x) String.Compare(x.ID,propertyName)=0)
                  
                      'Making sure that the Array.Find method worked...that f exists before trying to use it
                      If f IsNot Nothing Then
                        'Setting the instanceOfXYZ's property with the value of the Text property
                        'that is in the corresponding FieldUserControl object
                        pi.SetValue(instanceOfXYZ, f.Text, BindingFlags.GetField, Nothing, Nothing, Nothing)
                      End If
                    Next
                  End Sub

                  -Frinny

                  Comment

                  Working...