Solved

Binding a textbox to multiple dataset fields

Posted on 2004-08-15
11
1,624 Views
Last Modified: 2012-05-05
I'm new to C# and I have a hopefully easy question:

Is it possible to bind a text box with the following idea:

txtName.text = String.Format( "{0}, {1} {2}", row.LastName, row.FirstName, row.MiddleName);

where row is a row from a Typed Dataset.  This way the text field would write: "Johnson, Greg David".  This field would be readonly, so I would not have to worry about inputs.

Binding in C# seems very powerful, so I was thinking that this would be possible, but I'm not sure how to set it up.

G
0
Comment
Question by:gdbjohnson
  • 5
  • 4
  • 2
11 Comments
 
LVL 5

Expert Comment

by:knowlton
ID: 11806202
As long as you are not worrying about inputs (updating) the name....you can just do this:


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;

namespace WindowsApplication2
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private System.Windows.Forms.TextBox textBox1;
            private System.Windows.Forms.TextBox textBox2;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.textBox1 = new System.Windows.Forms.TextBox();
                  this.textBox2 = new System.Windows.Forms.TextBox();
                  this.SuspendLayout();
                  //
                  // textBox1
                  //
                  this.textBox1.Location = new System.Drawing.Point(24, 40);
                  this.textBox1.Name = "textBox1";
                  this.textBox1.Size = new System.Drawing.Size(208, 20);
                  this.textBox1.TabIndex = 0;
                  this.textBox1.Text = "textBox1";
                  //
                  // textBox2
                  //
                  this.textBox2.Location = new System.Drawing.Point(24, 72);
                  this.textBox2.Name = "textBox2";
                  this.textBox2.Size = new System.Drawing.Size(208, 20);
                  this.textBox2.TabIndex = 1;
                  this.textBox2.Text = "textBox2";
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(536, 266);
                  this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                                                              this.textBox2,
                                                                                                              this.textBox1});
                  this.Name = "Form1";
                  this.Text = "Names from DB";
                  this.Load += new System.EventHandler(this.Form1_Load);
                  this.ResumeLayout(false);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void Form1_Load(object sender, System.EventArgs e)
            {
                  DataSet ds;
                  ds = this.GenerateInternalDataSet("select FirstName, MiddleName, LastName from tblNames");
                  this.textBox1.Text = ds.Tables[0].Rows[0]["LastName"].ToString() + ", " + ds.Tables[0].Rows[0]["FirstName"].ToString() + " " + ds.Tables[0].Rows[0]["MiddleName"].ToString();
                  this.textBox2.Text = ds.Tables[0].Rows[1]["LastName"].ToString() + ", " + ds.Tables[0].Rows[1]["FirstName"].ToString() + " " + ds.Tables[0].Rows[1]["MiddleName"].ToString();
            }

            public DataSet GenerateInternalDataSet(string strSQL)
            {
                  OleDbConnection TempConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=names.mdb");
                  OleDbCommand TempCommand = new OleDbCommand(strSQL, TempConnection);
                  OleDbDataAdapter TempDataAdapter = new OleDbDataAdapter(TempCommand);
                  TempConnection.Open();                  
                  DataSet TempDataSet = new DataSet();
                  TempDataAdapter.Fill(TempDataSet);
                  return TempDataSet;                  
            }


      }
}
0
 
LVL 5

Expert Comment

by:knowlton
ID: 11806210
Here is a link to the zipped C# project:

http://www.robotzgame.com/junk/names_from_db.zip
0
 
LVL 5

Expert Comment

by:knowlton
ID: 11806215
The names.mdb would go in the same directory as your EXE  (Debug or Release, depending on what mode you are in) inside your project folder.
0
 
LVL 2

Author Comment

by:gdbjohnson
ID: 11809806
but this isn't a data binding.  You've just re-written what I've got in my question:

>this.textBox1.Text = ds.Tables[0].Rows[0]["LastName"].ToString() + ", " + ds.Tables[0].Rows[0]["FirstName"].ToString() + " " + ds.Tables[0].Rows[0]["MiddleName"].ToString();

is the same as:

>txtName.text = String.Format( "{0}, {1} {2}", row.LastName, row.FirstName, row.MiddleName);

but I was wondering if you could assign a data "binding" so that if I write

>this.BindingContext[dataset1, "myTable"].position++;

then the name will be updated appropriately.  I was hoping to avoid adding the above to a Current_Change event handler - setting the name manually.
0
 
LVL 5

Expert Comment

by:knowlton
ID: 11811135
Ohhhh.....ooops.

I see what you mean now.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 2

Author Comment

by:gdbjohnson
ID: 11811486
:)
0
 
LVL 5

Expert Comment

by:knowlton
ID: 11811510
This will take me more time....

There are other Experts who are a lot faster...hopefully they will see your post, since I don't know when I'll have time to look at this again.  :)

Good luck!
0
 
LVL 7

Expert Comment

by:psdavis
ID: 11823955
Take a look at 'Parse' and 'Format' in your DataBinding class.  It has exactly what you need.  Let me know if you need more details.
0
 
LVL 2

Author Comment

by:gdbjohnson
ID: 11825176
these are events.  Are you saying that I use the event to check that the binding values have changed, and then set the text box manually?
0
 
LVL 2

Author Comment

by:gdbjohnson
ID: 11826987
sorry... I see what you mean.

I can assign a binding between the text field and, say, the LastName field of my dataset.
In a defined method I can format the text field and append the first and middle names using the current Binding Context, and then use the ConvertEventHandler delegate to bind the procedure to the Format event.

The only problem is that this method results in poor code becaues I would need to bring in the First and Middle names externally from the method (right?), as a kind of global variable, and I'm not sure that I want to do this - especially while the same object (dataset) is involved in an event handler.

I was hoping that I could assign a field binding similar to the way Crystal Reports can create a (readonly) field using "{LastName}, {FirstName}" syntax.  That's the idea, anyways.

G
0
 
LVL 7

Accepted Solution

by:
psdavis earned 50 total points
ID: 11829795
Just got back to work. Sorry I missed your last response.

You're correct in your analysis of how to use Parse/Format.  It's unfortunately the only way to modify the binding parsing to/from a control.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Article by: Ivo
Anonymous Types in C# by Ivo Stoykov Anonymous Types are useful when  we do not need to follow usual work-flow -- creating object of some type, assign some read-only values and then doing something with them. Instead we can encapsulate this read…
Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now