How to Load selected columns data in DataGridView in C#

By FoxLearn 11/22/2024 8:19:04 AM   5.41K
To load selected columns of data into a DataGridView in C#, you can follow these steps.

How to Load selected columns data in DataGridView in C#?

Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "LoadSelectedCloumns" and then click OK

Drag and drop CheckedListBox, Button controls from Visual Toolbox onto your form1 designer, then design your form1 as shown below.

Form1.cs

c# load selected columns

Drag and drop a DataGridView control from Visual Toolbox onto your form2 designer.

Form2.cs

c# datagridview

You can add your connection string within the <connectionStrings> section of the app.config file.

<configuration>
  <connectionStrings>
    <add name="cn" connectionString="data source=.;initial catalog=NORTHWND;user id=sa;password=123@qaz;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

Once the connection string is added to your app.config file, you can access it in your C# code using the ConfigurationManager class.

If the ConfigurationManager class is not recognized, you may need to add a reference to System.Configuration. By right-clicking on References in your project, then select Add Reference.

Next, Choose System.Configuration from the list, then click OK.

If you want to load columns into the CheckedListBox dynamically, you can add the method below.

private void LoadColumnNames()
{
    // Assuming you want to display column names from the 'categories' table
    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
    {
        string sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Categories'";
        SqlDataAdapter sda = new SqlDataAdapter(sql, cn);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        foreach (DataRow row in dt.Rows)
        {
            checkedListBox.Items.Add(row["COLUMN_NAME"].ToString());
        }
    }
}

The LoadColumnNames method is added to populate the checkedListBox with column names dynamically from the database using the INFORMATION_SCHEMA.COLUMNS query. This ensures the user selects from actual available columns.

Add code to handle your form as below

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace LoadSelectedCloumns
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGetData_Click(object sender, EventArgs e)
        {
            string query = string.Empty;
            foreach (string s in checkedListBox.CheckedItems)
                query += s + ",";
            //Get columns
            query = query.Remove(query.Length - 1, 1);
            string sql = string.Format("select {0} from categories", query);
            using(SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
            {
                if (cn.State == ConnectionState.Closed)
                    cn.Open();
                //Execute query to retrieve data from sql database
                SqlCommand cmd = new SqlCommand(sql, cn) { CommandType = CommandType.Text };
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                using(DataTable dt = new DataTable("Categories"))
                {
                    // Fill data into DataTable
                    sda.Fill(dt);
                    // Pass the DataTable to Form2
                    using(Form2 frm = new Form2(dt))
                    {
                        frm.ShowDialog();
                    }
                }
            }
        }
    }
}

The btnGetData_Click method checks if at least one column is selected before proceeding with the query.

Form2.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LoadSelectedCloumns
{
    public partial class Form2 : Form
    {
        public Form2(DataTable dt)
        {
            InitializeComponent();
            dataGridView.DataSource = dt;
        }
    }
}

The DataGridView will display the DataTable passed from Form1.

This example allows the user to select specific columns from the CheckedListBox, fetch the corresponding data from the Categories table in the database, and display it in a DataGridView on Form2.

VIDEO TUTORIAL