Share via


How do I use one datagridview for multiple tabs in a tabcontrol

Question

Friday, September 24, 2010 12:50 AM

I'm using C#, visual studio 2008, sqlserver

I currently have a tabcontrol with 6 tabs.  I want to use one datagridview for all tabs.  I want the datagridview to use the same DataSet but with a different sql SELECT statement based on the tab selected.  I was initially trying to get one datagridview to display in two tabs. I added the datagridview to each tabpage. It seems that only the last tab displayed the datagridview.  The first tab displayed only white area.  My code for this is as follows,  my DataSet retrieval code is below that.  Any help wouild be appreciated.

      // 
      // tabPageBackground
      // 
      this.tabPageBackground.Controls.Add(this.dataGridViewEdges2);
      this.tabPageBackground.Location = new System.Drawing.Point(4, 22);
      this.tabPageBackground.Name = "tabPageBackground";
      this.tabPageBackground.Text = "Background";
      // 
      // dataGridViewEdges2
      // 
      this.dataGridViewEdges2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
      this.dataGridViewEdges2.Location = new System.Drawing.Point(0, 2);
      this.dataGridViewEdges2.Name = "dataGridViewEdges2";
      this.dataGridViewEdges2.RowHeadersVisible = false;
      // 
      // tabPageCombat
      // 
      this.tabPageCombat.Controls.Add(this.dataGridViewEdges2);
      this.tabPageCombat.Location = new System.Drawing.Point(4, 22);
      this.tabPageCombat.Name = "tabPageCombat";

      this.tabPageCombat.Text = "Combat";

Code to load Datasource for datagridview:

    public void LoadEdges2Grid(SqlConnection connection)
    {
      string edgesQueryString = "SELECT * FROM Edges WHERE Edges_Id = 1;";
      SqlCommand myCommand1 = new SqlCommand(edgesQueryString, connection);
      SqlDataAdapter myAdapter1 = new SqlDataAdapter();
      myAdapter1.TableMappings.Add("Table", "Edges");
      myCommand1.CommandType = CommandType.Text;
      myAdapter1.SelectCommand = myCommand1;
      edgesDS = new DataSet("Edges");

      myAdapter1.Fill(edgesDS);

      dataGridViewEdges2.DataSource = edgesDS;
      dataGridViewEdges2.DataMember = "Edges";
    }

All replies (2)

Tuesday, September 28, 2010 7:38 AM ✅Answered

Hi chrisitian smith,

 

Welcome to MSDN Forums!

 

Because of we’re using the same DataGridView instance between the two different tab pages. So we only can use Controls.Add method to place this DataGridView instance onto the current tab page.

 

Following I will show you my steps for implementing such function as you said:

1)       Create a WinForm project with the Form1

2)       Drag tabControl1 on to Form1

3)       Add a DataSource to this project through vs2010 DataSources panel

We add the Region data table in northwind database as this project’s data source.

4)       Drag dataGridView1 onto the tabPage1 and choose its data source to the above data source

5)       Double click the NORTHWNDDataSet.xsd in the solution explore to open this page

6)       Double click on the RegionTableAdapter to let vs2010 create a NORTHWNDDataSet.cs file automate.

7)       We can add to our method into this file, please look at following:

We can copy the Fill method from NORTHWNDDataSet.Designer.cs file, and then modify it to become to be our expected method.

using System.Data.SqlClient;

namespace WindowsFormsApplication1 {

   

   

    public partial class NORTHWNDDataSet {

    }

}

 

namespace WindowsFormsApplication1.NORTHWNDDataSetTableAdapters {

   

   

    public partial class RegionTableAdapter {

        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]

        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]

        [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]

        [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, false)]

        public virtual int FillByID(NORTHWNDDataSet.RegionDataTable dataTable, int Parameter1)

        {

            SqlCommand sqlcmd = new SqlCommand("SELECT RegionID, RegionDescription FROM Region WHERE (RegionID >= " + Parameter1 + ")", this.Connection);

            this.Adapter.SelectCommand = sqlcmd;

            if ((this.ClearBeforeFill == true))

            {

                dataTable.Clear();

            }

            int returnValue = this.Adapter.Fill(dataTable);

            return returnValue;

        }

    }

}

We will use this method to fill the dataGridView1 to display the record we wanted.

 

8)       Click on the tabControl1, and open its properties page, then click on events button to change the current page to the events page. Find the SelectedIndexChanged event, double click, the vs2010 will auto open the Form1.cs file and add a tabControl1_SelectedIndexChanged method to deal with the SelectedIndexChanged event.

9)       Then we need to modify and add some code into the Form1.cs file:

        private void Form1_Load(object sender, EventArgs e)

        {

            // we need to raise this event to let the dataGridView1 add onto the current tab page

            this.tabControl1_SelectedIndexChanged(this, null);

        }

 

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)

        {

            if (this.tabControl1.SelectedTab == this.tabPage2)

            {

                // call our method created above to fill the dataGridView1 with our excepted record

                this.regionTableAdapter.FillByID(this.nORTHWNDDataSet.Region, 3);

            }

            else

            {

                this.regionTableAdapter.Fill(this.nORTHWNDDataSet.Region);

            }

            // add the dataGridView1 onto the current tab page

            this.tabControl1.SelectedTab.Controls.Add(this.dataGridView1);

        }

 

10)   We can open the Form1.Designer.cs file to delete the following statement:

this.tabPage1.Controls.Add(this.dataGridView1);

Because of we raised the SelectedIndexChanged event to add the dataGridView1 to the current tab page at the Form1 loading time.

 

11)   After these steps, our project has finished now.

 

The code auto created by vs2010 is very useful for us, so we need to learn how to use these codes to help us work easier.

 

If there’s anything unclear, please feel free to let me know.

 

Best wishes,

Mike

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to the others community members reading the thread.

 

*****************************************************

[All-In-One Code Framework]

Sample world! You will get more from this world!

Welcome to the new world!


Friday, September 24, 2010 2:28 AM

Let me as the question a different way.  I have two tabs and added dataGridViewEdges2 to both tabs.  On entry to the application I retreive data from sql server and load my initial tab.  This works fine.  If I change tabs I call the TabControlSelect event  change my query and try to display the datagridviewEdges2 with the new data (different tab).   I don't recieve an error, the tab just has a blank space.   It's almost like the datagridview is not registering.  The basic code is below:

    private void OpenSqlConnection()
    {
      string connectionString = GetConnectionString();
      using (SqlConnection connection = new SqlConnection(connectionString))
      {
        connection.Open();
        Console.WriteLine("The connection is open");

        LoadEdges2Grid(connection, edgesQueryString);
        AddEdges2SelectColumn();
        
        tabControlEdges2.SelectedTab = this.tabPageCombat;
      }
    }


   private void tabControlEdges2_Selected(Object sender, TabControlEventArgs e)
    {
 
      this.LoadEdges22Grid();

     }


    public void LoadEdges22Grid()
    {
            string connectionString = GetConnectionString();
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
              connection.Open();
              Console.WriteLine("The connection is open");

              string edgesQueryString1 = "SELECT * FROM Edges WHERE Edges_Id = 3;";
              SqlCommand myCommand1 = new SqlCommand(edgesQueryString1, connection);
              SqlDataAdapter myAdapter1 = new SqlDataAdapter();
              myAdapter1.TableMappings.Add("Table", "Edges");
              myCommand1.CommandType = CommandType.Text;
              myAdapter1.SelectCommand = myCommand1;
              edgesDS = new DataSet("Edges");

              myAdapter1.Fill(edgesDS);

              dataGridViewEdges2.DataSource = edgesDS;
              dataGridViewEdges2.DataMember = "Edges";
            }
    }