Step 1: 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
Step 2: Design your form as below
Form1

Form2

Step 3: Add a connection string to the app.config file as below
<configuration>
<connectionStrings>
<add name="cn" connectionString="data source=.;initial catalog=NORTHWND;user id=sa;[email protected];" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Step 4: Add code to handle your form as below
Form1
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 to datatable
sda.Fill(dt);
using(Form2 frm = new Form2(dt))
{
frm.ShowDialog();
}
}
}
}
}
}
Form2
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;
}
}
}
VIDEO TUTORIALS