ComboBox – DataGridView Sample


            The Article Demonstrate the how to change the DataSource Property of DataGridView Dynamically.

Requirements:
  • ComboBox Control
  • DataGridView Control
Description:
  • The method is so easy to handle.
  • Here, I am taken an XML file as DataBase file.
  • The Article shows displaying data into DataGridView Control of table name selected from the ComboBox Control.
Arrangements:
  • Create a new instance of the System.Data.DataSet class.
              DataSet Dset = new DataSet();
Listing 1
  • Now, on the Form_Load event handler read an XML file using DataSet Object.
              Dset.ReadXml(“..\..\XMLData.xml”);
Listing 2
  • Then add all the TableName avail in the DataSet Object to the ComboBox items collection. Result is displayed in Figure 1.
           
                for (intitem=0; item < Dset.Tables.Count;item++ )
                   {
                             comboBox1.Items.Add(Dset.Tables[item].TableName.ToString());
                   }       
Listing 3
Figure-1


 Figure 1
  • After this, set the DataSource property of DataGridView to the selected item of ComboBox.
                   private voidcomboBox1_SelectedIndexChanged(object sender, EventArgs e)
                   {
                             dataGridView1.DataSource = null;
                             dataGridView1.DataSource = Dset.Tables[comboBox1.Text];
                   }
Listing 4
Output: Following snapshots shows the intended result.
Figure - 2
Figure 2
Figure -3
Figure 3
Summary:
          In this session, we have seen the ComboBox – DataGridView operation for displaying table data dynamically from the selected item of ComboBox Control.
Regards,
Mayur Dighe
http://ImmortalDotNet.blogspot.com
http://MayurDighe.wordpress.com