Solved

Binding a textbox to multiple dataset fields

Posted on 2004-08-15
11
1,628 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
C# Error - Add Failed 12 77
c# find out if selected(highlighted) text in textbox was replaced or removed 9 59
C# Offline Apllication 5 48
how to read json value 2 27
Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

943 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

7 Experts available now in Live!

Get 1:1 Help Now