locked
Binding controls to data in DataGridView RRS feed

  • Question

  • Hi All,

    I use the following (this was shown by Martin in one of the threads in the forum)  to bind data to DataGridView and it works fine. No problems here

    dim cn As OleDbConnection = New OleDbConnection ("Provider=Microsoft.jet.4.0;data source=C:\boooks.mdb")

    cn.open()

    dim cmd as OleDbCommand = new OleDbCommand ("Select * FROM Publishers", cn)

    dim myDA as OleDbDataAdapter = New OleDbDataAdapter (cmd)

    dim ds as DataSet = New DataSet()

    myDA.fill(ds, "MyTable")

    DataGridView1.DataSource = ds.Tables("MyTable").DefaultView

    cn.close()

     

    I use the following to bind controls to the data in the DataGridview and that is where I have troubles with:

    in the " Private Sub DataGridView1_RowEnter (............) "  I use the these

    TextBox1 = DataGridview1.Rows(e.RowIndex).Cell(0).Value.ToString()

    TextBox2 = DataGridview1.Rows(e.RowIndex).Cell(1).Value.ToString()

    and a few more a long with labels

     

    Am I doing something wrong or am I missing something here?

     

    Alternative: how do I bind controls to the database with the provided the connection above?

     

    Thanks.

    LA Bob




    • Edited by LA_Bob Wednesday, October 26, 2011 5:23 PM
    Wednesday, October 26, 2011 4:48 PM

Answers

  • Bob,

    Here's how you make use of databinding, to bind the TextBoxes and the Grid to the same DataSource, thereby making them stay in sync automatically, as Jose was alluding to. Only I do it in code ... most of the time I hate the darn wizards too. ;0)

    I don't advocate putting your DataAccess directly in your Form (it should be separated out to a different class), but that's got nothing to do with your question ... I'm just mentioning it for your future consideration. Anyway, change your code like this (and hopefully I'll get the VB syntax correct):

    dim ds as DataSet = New DataSet()
    myDA.fill(ds, "MyTable")
    
    ' Does not need to bind to DefaultView, just the Table
    Me.DataGridView1.DataSource = ds.Tables("MyTable")
    
    ' Now the TextBoxes
    Me.TextBox1.DataBindings.Add("Text", ds.Tables("MyTable"), "MyColumnOne")
    Me.TextBox2.DataBindings.Add("Text", ds.Tables("MyTable"), "MyColumnTwo")
    
    
    


    That's all you need to do ... whenever the user moves to a different row in the grid, the contents of the TextBoxes will automatically change to the values in the new row.


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    • Marked as answer by LA_Bob Thursday, October 27, 2011 5:11 PM
    • Unmarked as answer by LA_Bob Thursday, October 27, 2011 5:11 PM
    • Marked as answer by LA_Bob Thursday, October 27, 2011 5:12 PM
    Thursday, October 27, 2011 3:40 PM

All replies

  • You didnt specify to which property of Textbox you want to add a value. Usually this property is Text.

    So do:

    TextBox1.Text = DataGridview1.Rows(e.RowIndex).Cell(0).Value.ToString()
    


    and so on..

    Hope it helps,

    bye


    Mitja
    Wednesday, October 26, 2011 5:25 PM
  • you can also shorten this code to:

    TextBox1.Text = DataGridview1(0, RowIndex).Value.ToString()
    TextBox2.Text = DataGridview1(1, RowIndex).Value.ToString()
    

    this is the same as your code of getting data from datagridview., just shorter.


    Mitja
    Wednesday, October 26, 2011 5:27 PM
  • Hi Bonca,

     

    I am sorry......... fat finger...........

    TextBox1.text = DataGridview1.Rows(e.RowIndex).Cell(0).Value.ToString()

    This is what I used and it did not show anything when the a row is highlighted.

    Thanks,

    LA Bob

     

    Wednesday, October 26, 2011 5:47 PM
  • Why not take advantage of Forms data binding?  A DGV will change the current record in the underlying CurrencyManager object.  If you bind your textboxes to the same CurrencyManager object, the updating of the textboxes will be 100% automatic.
    Jose R. MCP
    Wednesday, October 26, 2011 6:11 PM
  • Hi WebJose,

     

    I am not sure I understand that, Would you mind to elaborate on what you said?

     

    Thanks,

    LA Bob

    Wednesday, October 26, 2011 6:22 PM
  • Basically this:  Take a form and add a DGV, then add the textboxes.  Make sure all these are inside the same container (no panels or groupboxes anywhere; if you need these, we can discuss later).  Then assign the same data source to the DGV and all textboxes using the Visual Studio designer and test.  You'll see that, without writing any code, the textboxes automatically update themselves whenever you select a different row in the DGV.

    If you are obtaining the data source during runtime (maybe creating a list at runtime and assigning that list to the DataSource property of the DGV), then you assign that same data source to all your text boxes too.


    Jose R. MCP
    Wednesday, October 26, 2011 6:28 PM
  •  

    Hi WebJose,

    When I binded data to datagridview through data source configuration wizard and binded all controls to datagridview and they all worked fine.  I do not want to do it this way because my labtop screen is not that big and over time it will be overcrowded.  I try to write codes whenever is possible and help me learn as well because I am kind a new to this .NET. 

     

    Thanks,

    LA Bob


    • Edited by LA_Bob Wednesday, October 26, 2011 6:38 PM
    Wednesday, October 26, 2011 6:37 PM
  • I don't understand.   You say all worked fine.  What's the problem now?

    Remember that a Visual Studio wizard ends up just writing stuff for you in code files or code designer files.  I don't understand why the use of the wizard will (over time) overcrowd your screen.  I mean, it fits or it doesn't fit.  Or am I misunderstanding?

    Let's get things clear:

    1. Did you try my suggestion?  If you did, did it work appropriately and as expected?  If not, please explain why not.  If you can also show a screenshot, please do so.  This forum allows two pictures per post (see the toolbar, the next button after the  "</>" button).
    2. What do you mean by "over time it will be overcrowded"?  What is overcrowding your screen:  The Visual Studio Data Source Configuration Wizard, or the form you are designing?

    Jose R. MCP
    Wednesday, October 26, 2011 6:43 PM
  • Here is what I meant:

    When I binded to database through data source configuration wizard for one datagridview, I would get 2 or 3 icons resides on the bottom of the screen.  If you have 5 or 6 datagridview that you have to bind to database, that is just to many these icons............. the form that I am working on.........

    How come it does not work through that binding as I mentioned above?

    TextBox1.text = DataGridview1.Rows(e.RowIndex).Cell(0).Value.ToString()

    Thanks,

    LA Bob

     

    Wednesday, October 26, 2011 6:59 PM
    1. Create a new Windows Forms application.
    2. Add a new DataGridView control to Form1.
    3. Configure the DataGridView's data source using the Data Source Configuration Wizard.  This creates 3 components:  1 dataset, 1 binding source, 1 table adapter.
    4. Add as many textboxes to Form1 as needed.
    5. For each textbox, select it and go to the Properties window.
    6. Expand Databindings, and find the Text property.
    7. Click to get the editor (see screenshot #2).
    8. In this editor, expand the binding source and select the column that you need to display.
    9. Save and run.  Voilá!

    Screenshot 1:  This is how Form1 looks like after configuration of the data source:

    The highlighted component called tblEmpleadosBindingSource is also the data source for the textboxes.  See this next screenshot:

    That's it.


    Jose R. MCP
    Wednesday, October 26, 2011 7:33 PM
  • you have three components per binding for one datagridview.  Say you have 5 or 6 datagridview and you have to bind them to different tables, that 15 or 18 components and they reside at the bottom of the screen.  With a laptop that has small screen, it will be hard to work with so many things on your design form.

    through coding, I think I learn and understand more about .NET

    Thanks,

    LA Bob

    Wednesday, October 26, 2011 7:48 PM
  • If you select the row, then you have to do:

    TextBox1.Text = DataGridview1(0, CurrentCell.RowIndex).Value.ToString()
    TextBox2.Text = DataGridview1(1, CurrentCell.RowIndex).Value.ToString()
    



    Mitja
    Wednesday, October 26, 2011 7:51 PM
  • Hi Bonca,

     

    Thank you for your help.  I tried that and it did not work.  I don't understand why this did not work:

    TextBox1.text = DataGridview1.Rows(e.RowIndex).Cell("0").Value.ToString()

    TextBox2.text = DataGridview1.Rows(e.RowIndex).Cell("1").Value.ToString()

     

    Thanks,

    LA Bob

    Wednesday, October 26, 2011 8:38 PM
  • Ok, if you have so many DGV's, then maintain a dataset in memory with multiple datatables in it (one table per DGV).  This code shows how to obtain the data for one dataset and also shows how to set the data bindings (so the textboxes change automatically with the selection of row in the DGV):

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    
    namespace WindowsFormsApplication1
    {
        public partial class FormA : Form
        {
            private DataSet _myData;
            public FormA()
            {
                InitializeComponent();
            }
            private void FormA_Load(object sender, EventArgs e)
            {
                using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.CS))
                {
                    using (SqlCommand cmd = new SqlCommand("Select * From dbo.tblEmpleados", conn))
                    {
                        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                        _myData = new DataSet();
                        adapter.Fill(_myData);
                    }
                }
                dataGridView1.DataSource = _myData.Tables[0];
                textBox1.DataBindings.Add(new Binding("Text", _myData.Tables[0], "Nombre", true));
                textBox2.DataBindings.Add(new Binding("Text", _myData.Tables[0], "Apellido", true));
            }
        }
    }
    
    



    Jose R. MCP
    Wednesday, October 26, 2011 9:33 PM
  • Hi WebJose,

     

    Thank you for your help. I am working in VB.NET.  Could you please translate that into VB.NET?  I am sorry to bother you with this.

     

    Thanks,

    LA Bob

    Wednesday, October 26, 2011 10:07 PM
  • Sorry, no.  I don't do VB.net.  Find an online translator.  This is the first result from Google (searched for "C# to vb"):  http://www.developerfusion.com/tools/convert/csharp-to-vb/

    Jose R. MCP
    Wednesday, October 26, 2011 10:17 PM
  • Hi Jose,

     

    Thank you.  I used the converter online and this is what I got.

     

    Imports System.Collections.Generic
    Imports System.ComponentModel
    Imports System.Data
    Imports System.Drawing
    Imports System.Linq
    Imports System.Text
    Imports System.Windows.Forms
    Imports System.Data.SqlClient

    Namespace WindowsFormsApplication1
    Public Partial Class FormA
    Inherits Form
    Private _myData As DataSet
    Public Sub New()
    InitializeComponent()
    End Sub
    Private Sub FormA_Load(sender As Object, e As EventArgs)
    Using conn As New SqlConnection(Properties.Settings.[Default].CS)
    Using cmd As New SqlCommand("Select * From dbo.tblEmpleados", conn)
    Dim adapter As New SqlDataAdapter(cmd)
    _myData = New DataSet()
    adapter.Fill(_myData)
    End Using
    End Using
    dataGridView1.DataSource = _myData.Tables(0)
    textBox1.DataBindings.Add(New Binding("Text", _myData.Tables(0), "Nombre", True))
    textBox2.DataBindings.Add(New Binding("Text", _myData.Tables(0), "Apellido", True))
    End Sub
    End Class
    End Namespace


    There are two errors:

    Error 1 Name 'Properties' is not declared.

    Error 2 'Form1' is a type in 'WindowsApplication1' and cannot be used as an expression.

    Thanks,
    LA Bob

     

     

     

    Thursday, October 27, 2011 12:43 AM
  • Like I said, I don't do VB.net.  Your answer is there.  Figure out those errors.  Just an FYI, this second example used a form called FormA, not Form1, for whatever is worth.
    Jose R. MCP
    Thursday, October 27, 2011 5:02 AM
  • Thank you Jose.

    My knowledge of VB.NET is limited and I cannot figure out those errors............. Again, thank you for your help.

     

    Let me start my question over again.

     

    Why the following statements do not work

     

    TextBox1.text = DataGridview1.Rows(e.RowIndex).Cell(0).Value.ToString()

    TextBox2.text = DataGridview1.Rows(e.RowIndex).Cell(1).Value.ToString()

     

    with the following connection

     

    dim cn As OleDbConnection = New OleDbConnection ("Provider=Microsoft.jet.4.0;data source=C:\boooks.mdb")

    cn.open()

    dim cmd as OleDbCommand = new OleDbCommand ("Select * FROM Publishers", cn)

    dim myDA as OleDbDataAdapter = New OleDbDataAdapter (cmd)

    dim ds as DataSet = New DataSet()

    myDA.fill(ds, "MyTable")

    DataGridView1.DataSource = ds.Tables("MyTable").DefaultView

    cn.close()

     

    Thanks,

    LA Bob

    Thursday, October 27, 2011 11:50 AM
  • Bob,

    Here's how you make use of databinding, to bind the TextBoxes and the Grid to the same DataSource, thereby making them stay in sync automatically, as Jose was alluding to. Only I do it in code ... most of the time I hate the darn wizards too. ;0)

    I don't advocate putting your DataAccess directly in your Form (it should be separated out to a different class), but that's got nothing to do with your question ... I'm just mentioning it for your future consideration. Anyway, change your code like this (and hopefully I'll get the VB syntax correct):

    dim ds as DataSet = New DataSet()
    myDA.fill(ds, "MyTable")
    
    ' Does not need to bind to DefaultView, just the Table
    Me.DataGridView1.DataSource = ds.Tables("MyTable")
    
    ' Now the TextBoxes
    Me.TextBox1.DataBindings.Add("Text", ds.Tables("MyTable"), "MyColumnOne")
    Me.TextBox2.DataBindings.Add("Text", ds.Tables("MyTable"), "MyColumnTwo")
    
    
    


    That's all you need to do ... whenever the user moves to a different row in the grid, the contents of the TextBoxes will automatically change to the values in the new row.


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    • Marked as answer by LA_Bob Thursday, October 27, 2011 5:11 PM
    • Unmarked as answer by LA_Bob Thursday, October 27, 2011 5:11 PM
    • Marked as answer by LA_Bob Thursday, October 27, 2011 5:12 PM
    Thursday, October 27, 2011 3:40 PM
  • Hi Bonnie,

     

    It works.  Thank you to you.

     

    I was able to bind data to controls .............  Using the String.format"{0:C}" I was able to display numbers like: 11.22 or 10.50

     

    I am working on the following and so far I have not been able to figure it out just yet.  Wondering if you know how to do this................

    using this as an example:  Me.TextBox1.DataBindings.Add("Text", ds.Tables("MyTable"), "MyColumnOne")

    to combine two fields or cells and display them on one control like this:

    cell one: 123

    cell two: 456-789-000

    combine these two cells and display it in one control as 123-456-789-000.

     

    The worst case is to read  and display them in two different controls............... I just thought if it was possible to read & combine them into one control................ 

     

    Again, Thank you very much for your help.

    LA Bob





    • Edited by LA_Bob Thursday, October 27, 2011 5:32 PM
    Thursday, October 27, 2011 5:20 PM
  • > to combine two fields or cells and display them on one control like this: cell one: 123cell two: 456-789-000 combine these two cells and display it in one control as 123-456-789-000.


    use the DataColumn.Expression (for create a 'virtual' column).
    an example is here

    • Edited by Malobukv Thursday, October 27, 2011 5:32 PM
    Thursday, October 27, 2011 5:28 PM
  • Hi Malobukv,

     

    How do you translate that into this (Me.TextBox1.DataBindings.Add("Text", ds.Tables("MyTable"), "MyColumnOne")?

     

    Thanks,

    LA Bob

    Thursday, October 27, 2011 6:00 PM
  • > How do you translate that into this (Me.TextBox1.DataBindings.Add("Text", ds.Tables("MyTable"),"MyColumnOne")?
     

    using System.Data;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                // create DataTable
                var dt = new DataTable("MyTable");
                dt.Columns.Add("cell one", typeof(int));
                dt.Columns.Add("cell two", typeof(string));
                dt.Rows.Add(123, "456-789-000");
                // create DataSet and add DataTable
                var ds = new DataSet();
                ds.Tables.Add(dt);
                // create 'virtual' cell   
                dt.Columns.Add("two cells", typeof(string), "[cell one]+'-'+[cell two]");
                // create TextBox and bind to DataTable
                var tb = new TextBox();
                tb.Parent = this;
                tb.DataBindings.Add("Text", ds.Tables["MyTable"], "two cells");
            }
        }
    }
    

    • Proposed as answer by Malobukv Thursday, October 27, 2011 7:41 PM
    Thursday, October 27, 2011 6:11 PM
  • Hi Malobukv,
    Thank you for your help.
    Using the converter that provided by Joe and I got this:
    Imports System.Data
    Imports System.Windows.Forms
    
    Namespace WindowsFormsApplication1
    	Public Partial Class Form1
    		Inherits Form
    		Public Sub New()
    			' create DataTable
    			Dim dt = New DataTable("MyTable")
    			dt.Columns.Add("cell one", GetType(Integer))
    			dt.Columns.Add("cell two", GetType(String))
    			dt.Rows.Add(123, "456-789-000")
    			' create DataSet and add DataTable
    			Dim ds = New DataSet()
    			ds.Tables.Add(dt)
    			' create 'virtual' cell   
    			dt.Columns.Add("two cells", GetType(String), "[cell one]+'-'+[cell two]")
    			' create TextBox and bind to DataTable
    			Dim tb = New TextBox()
    			tb.Parent = Me
    			tb.DataBindings.Add("Text", ds.Tables("MyTable"), "two cells")
    		End Sub
    	End Class
    End Namespace
    It has an error as: Namespace statements can occur only at file or namespace level.  Could not correct the error.

     

    Thanks,

    LA Bob

    Thursday, October 27, 2011 7:02 PM
  • > Using the converter that provided by Joe and I got this: [...] It has an error as: Namespace statements can occur only at file or namespace level.


    i don't know vb.net, sorry. i've translated c# to vb.net with reflector.
    below is a result. not sure it's correct, but try.

    Namespace WindowsFormsApplication1
       Public Class Form1
        Inherits Form
        ' Methods
        Public Sub New()
            Dim dt As New DataTable("MyTable")
            dt.Columns.Add("cell one", GetType(Integer))
            dt.Columns.Add("cell two", GetType(String))
            dt.Rows.Add(New Object() { &H7B, "456-789-000" })
            Dim ds As New DataSet
            ds.Tables.Add(dt)
            dt.Columns.Add("two cells", GetType(String), "[cell one]+'-'+[cell two]")
            New TextBox() { _
                .Parent = Me _
            }.DataBindings.Add("Text", ds.Tables.Item("MyTable"), "two cells")
        End Sub
    
        Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            If (disposing AndAlso (Not Me.components Is Nothing)) Then
                Me.components.Dispose
            End If
            MyBase.Dispose(disposing)
        End Sub
    
        Private Sub InitializeComponent()
            Me.components = New Container
            MyBase.AutoScaleMode = AutoScaleMode.Font
            Me.Text = "Form1"
        End Sub
    
    
        ' Fields
        Private components As IContainer = Nothing
      End Class
    
      Friend Class Program
          ' Methods
          <STAThread> _
          Private Shared Sub Main()
      End Class
    End Namespace
    
     
    
    

    Thursday, October 27, 2011 7:40 PM
  • Bob, don't focus so much on the code that Malobukv posted ... focus instead on the concept behind what he's trying to tell you. IOW ... you add an extra column to your DataTable, it uses an Expression to concatenate two other columns values together. You databind to that new column. That's the gist of what he's saying. So, try this:

    myDA.fill(ds, "MyTable")
    ds.Tables("MyTable").Columns.Add("MyColumnThree");
    ' UPDATE: Changed goof, should NOT be Items
    ' ds.Tables("MyTable").Items("MyColumnThree").Expression = 
         "MyColumnOne + '-' + MyColumnTwo"
    ds.Tables("MyTable").Columns("MyColumnThree").Expression = 
         "MyColumnOne + '-' + MyColumnTwo"
    
    ' Does not need to bind to DefaultView, just the Table
    Me.DataGridView1.DataSource = ds.Tables("MyTable")
    
    ' Now the TextBoxes
    Me.TextBox1.DataBindings.Add("Text", ds.Tables("MyTable"), "MyColumnOne")
    Me.TextBox2.DataBindings.Add("Text", ds.Tables("MyTable"), "MyColumnTwo")
    Me.TextBox3.DataBindings.Add("Text", ds.Tables("MyTable"), "MyColumnThree")
    
    
    
    

    Can you get it to work now?


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    • Edited by BonnieBMVP Saturday, October 29, 2011 2:33 PM Changed a goof from Items to Columns in Expression setting
    Thursday, October 27, 2011 8:22 PM
  • > Bob, don't focus so much on the code that Malobukv posted [...] So, try this ...

     
    great, but it would be better if you'll help to translate C# to VB.NET

    Thursday, October 27, 2011 8:42 PM
  • I don't know VB any better than you do ... I also use online translators when I need to ... and they're not always perfect. That's why I usually only post a few VB code snippets, rather than an entire program (even a simple program, such as yours).

    I wasn't dissing your code ... I was simply trying to focus Bob on the relevant parts of it, the parts that related to his question.


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Thursday, October 27, 2011 8:54 PM
  • > I don't know VB any better than you do ...


    unfortunately, I do not know vb.net
    'my' vb.net code was created from compiled c# with .net reflector (http://en.wikipedia.org/wiki/.NET_Reflector)

    Thursday, October 27, 2011 9:20 PM
  • Hi Bonnie,

     

    I did copy & paste and got a few errors....... I will try to fix it later and let you know.

     

    Thank you Bonnie & Malokuv

     

    LA Bob

    
    
    Thursday, October 27, 2011 10:09 PM
  • Hi Bonnie,

     

    I could not make it to work............... I think I will use two controls, instead of one to display two fields.............. I am going to give up on trying to make it to work. 

    If the other way would work I would use something like this:

    textbox1.text = datagridview1.Rows(e.RowIndex).Cells("ColumnOne").Value.ToString() + "-" + datagridview1.Rows(e.RowIndex).Cells("ColumnTow").Value.ToString()

     

    This way, you could read two fields and display them in one control.  Any way, thank you all for helping me.

    LA Bob


    • Edited by LA_Bob Friday, October 28, 2011 2:28 PM
    Friday, October 28, 2011 2:23 PM
  • Bob --- the code that both I and Malobukv posted above, *does* work. I knew it worked when I posted it, but just to be sure I just did a quick test. It works fine. Maybe you could post what you tried and we can take a look at it and see what you missed ...
    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Friday, October 28, 2011 3:23 PM
  • Hi Bonnie,

    I set  up the binding connection just as a bove and added what you showed in your previous post.

    The error I got is "Items" is not a member of "System.Data.DataTable

    Thannks,

    LA Bob

     

     

    Friday, October 28, 2011 5:15 PM
  • Sorry Bob ...  my slip-up because of a bad VB translation. It should be Columns, not Items:

    ds.Tables("MyTable").Columns("MyColumnThree").Expression =
         "MyColumnOne + '-' + MyColumnTwo"

    BTW -- I went back and fixed that post.


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com

    • Edited by BonnieBMVP Saturday, October 29, 2011 2:35 PM
    Friday, October 28, 2011 5:24 PM
  • Hi Bonnie,

    I am sorry for late reply.  I was busy running around over the weekend.................. I tried the following:

     

    ds.Tables("MyTable").Columns.Add("MyColumnThree")   ' Error: Column named "MyColumnThree" already belongs to this DataTable.

    ds.Tables("MyTable").Columns("MyColumnThree").Expression = "MyColumnTwo + '-' + MyColumnThree"

    I was trying to bind/read cell two and cell three (or field one & field two) and display them in ONE textbox and not TWO separate controls as you showed in your example.

    Thanks,

    LA Bob

     

    Monday, October 31, 2011 1:53 PM
  • ds.Tables("MyTable").Columns.Add("MyColumnThree")   ' Error: Column named "MyColumnThree" already belongs to this DataTable.

    The error is obviously because you already had a column called "MyColumnThree" ... you're supposed to be adding a new column to the DataTable, one where you can concatenate the values from the two already-existing columns.

    I was trying to bind/read cell two and cell three (or field one & field two) and display them in ONE textbox and not TWO separate controls as you showed in your example.

    Well, yes, of course ... I simply copy/pasted from the code I had posted earlier and added the 3rd TextBox to bind to the MyColumnThree. I was simply showing you the concept. Obviously, you need to tweak that to only bind one existing TextBox to the new column.

    Not sure what you mean by your "cell two/cell three and field one/field two" comment ...


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Monday, October 31, 2011 2:21 PM
  • Hi Bonnie,

     

    Ok. Here is how I have it setup.

     

    dim cn As OleDbConnection = New OleDbConnection ("Provider=Microsoft.jet.4.0;data source=C:\boooks.mdb")

    cn.open()

    dim cmd as OleDbCommand = new OleDbCommand ("Select * FROM Publishers", cn)

    dim myDA as OleDbDataAdapter = New OleDbDataAdapter (cmd)

    dim ds as DataSet = New DataSet()

    myDA.fill(ds, "MyTable")

    DataGridView1.DataSource = ds.Tables("MyTable")

    ds.Tables("MyTable").Columns.Add("MyColumnThree")   ' Error: Column named "MyColumnThree" already belongs to this DataTable

    ds.Tables("MyTable").Columns("MyColumnThree").Expression = "MyColumnTwo + '-' + MyColumnThree"

     

    cn.close()

     

    Cell two/Cell three mean: To bind cell one in one column and cell two in another column and display them in one control and not two separate controls.

     

    Thanks,

    LA Bob

    Monday, October 31, 2011 3:43 PM
  • There's a "MyColumnThree" column  in the Publishers table in your database?!?
    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Monday, October 31, 2011 3:52 PM
  • Hi Bonnie,

     

    Say, I have this database setup like this...............

    ID                     NumberOne                               NumberTwo

    1                      123                                            456-789-000

    2                      000                                            123-456-789

     

    I would like to bind controls and display them in this fashion.............

    TextBox1.DataBindings.Add("Text", ds.Tables("MyTable"), "ID")    ' No problems here

     

    For the TextBox2  I would like to bind/read and display " 123-456-789-000 " in TextBox2, which mean, I would have to bind "cell one is 123" in one column and cell two is " 456-798-000 " in another column and display them in ONE Control, TextBox2.

     

    I hope this clear up any confusion...............

     

    Thanks,

    LA Bob

    Monday, October 31, 2011 3:53 PM
  • OK ... then your code would look like this:

    myDA.fill(ds, "MyTable")
    ds.Tables("MyTable").Columns.Add("NumberThree");
    ds.Tables("MyTable").Columns("NumberThree").Expression = 
         "NumberOne+ '-' + NumberTwo"
    
    Me.DataGridView1.DataSource = ds.Tables("MyTable")
    
    Me.TextBox1.DataBindings.Add("Text", ds.Tables("MyTable"), "ID")
    Me.TextBox2.DataBindings.Add("Text", ds.Tables("MyTable"), "NumberThree")
    

    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    • Edited by BonnieBMVP Monday, October 31, 2011 4:06 PM
    Monday, October 31, 2011 4:04 PM
  • Hi Bonnie,

     

    I tried to tweak it but it did not do anything and would give me the same error.........  I am giving up.   Thank you very much for your help.

     

    Thanks,

    LA Bob

    Monday, October 31, 2011 5:54 PM
  • Bob, here's the question you should be asking yourself: how can the column already exist if you are only adding it one place? There are only two possibilities:

    1. It's a column name that is already in your database table (the Fill is creating all the same columns in your DataTable that are in the database table, since you're doing a SELECT *).
    2. The method where you're adding the new column is getting called more than once.

    Why don't you simply check for the existence of that column before you add it? You can still leave the line that sets the Expression. You can use the .Contains() method to check for it's existence.

    If ds.Tables("MyTable").Columns.Contains("NumberThree")
        ' already exists, don't add it
    

     


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Monday, October 31, 2011 6:05 PM
  • Hi Bonnie,

     

    Thank you very much for your help and Happy Halloween.  I stopped trying to make it work.

     

    Thanks,

    LA Bob

    Monday, October 31, 2011 8:19 PM
  • Oh ... Wow! Well, ok ... but it's your loss. It's really not hard and I think it would broaden your understanding of how databinding works. And the problem that's stopping you has nothing to do with databinding. But ... I guess I'm just more persistent (or stubborn?) than you are ...  ;0)  ;0)

    Happy Halloween! =0)


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Monday, October 31, 2011 8:29 PM
  • Hi Bonnie,

     

    I may come back later and give it another try.  You ARE persistent and I like that.......... Thank you for your help.

     

    Thanks,

    LA Bob

    Tuesday, November 1, 2011 1:21 PM
  • ... or just plain old stubborn! ;0)

    I'm glad that we could at least give you some "food for thought". Let me know if you get around to trying again and whether or not you can get it to work.


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Tuesday, November 1, 2011 2:39 PM
  • Hi Bonnie,

    Thank you.  I had this little project here was written in VB 6.0 and I am trying to rewrite it in VB.NET.  I am working on it but it is a little slow and I don't know how long it's gonna take to complete it.  I hope it won't take too long (a year to more because it has a few thousand lines of codes).  If I get stuck or something, can I holler or call out your name for help?  I hope you won't mind me doing that.  Thanks in advance.

     

    Thanks,

    LA Bob

    Tuesday, November 1, 2011 3:34 PM
  • Hey Bob,

    The best thing to do if you get stuck on something, and you'd like input from me, would be to post the question in a new thread here on the forums, then send me an email with the link to the thread. That's the only way I know of to let me know about it. But please don't just email a question to me ... doing it through the forums is better because you'll get others helping too. Besides, I don't know everything!!!  ;0)   ;0)

    Good luck with your project!


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Tuesday, November 1, 2011 3:47 PM
  • Hi Bonnie,

    May I have your email address please?

     

    Thanks,

    LA Bob

    Tuesday, November 1, 2011 5:38 PM
  • Bob -- go to my blog, click on my Profile. My email is there.
    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Tuesday, November 1, 2011 6:18 PM