2
Answers

How to query the columns according to the checkedListBox

Photo of Mehmet Fatih

Mehmet Fatih

1y
599
1

I am trying to query the columns from which data will be retrieved based on the selected item with checkedListBox. But I couldn't understand the logic. Would you help me with this topic? I am using c#.

Answers (2)

0
Photo of Mehmet Fatih
814 948 49.2k 1y

Thanks for your intrest, Muhammed Imran Ansari. When I try your codes, I am getting this error.

 

How can we send hidden checkboxlist value?

0
Photo of Muhammad Imran Ansari
252 7.6k 328.1k 1y

To query columns from a database based on the selections made in a CheckedListBox in C#, you can use the following example as a reference. (I'm assuming you are using SQL database)

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace CheckedListBoxExample
{
    public partial class Form1 : Form
    {
        private const string connectionString = "YOUR_CONNECTION_STRING"; // Replace with your actual connection string

        public Form1()
        {
            InitializeComponent();
            PopulateCheckedListBox(); // Populates the CheckedListBox with column names
        }

        private void PopulateCheckedListBox()
        {
            using (var connection = new SqlConnection(connectionString))
            {
                string query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YOUR_TABLE_NAME'"; // Replace with your actual table name

                var command = new SqlCommand(query, connection);
                connection.Open();
                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    checkedListBox1.Items.Add(reader["COLUMN_NAME"].ToString());
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<string> selectedColumns = new List<string>();

            foreach (var item in checkedListBox1.CheckedItems)
            {
                selectedColumns.Add(item.ToString());
            }

            using (var connection = new SqlConnection(connectionString))
            {
                string query = "SELECT " + string.Join(", ", selectedColumns) + " FROM YOUR_TABLE_NAME"; // Replace with your actual table name

                var command = new SqlCommand(query, connection);
                connection.Open();
                var adapter = new SqlDataAdapter(command);
                var table = new DataTable();
                adapter.Fill(table);

                dataGridView1.DataSource = table;
            }
        }
    }
}