Windows Forms: How to Load selected columns data in DataGridView in C#
By FoxLearn 7/29/2017 4:20:58 PM 5.05K
How to load selected columns data in DataGridView using c#
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;password=123@qaz;" 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
- How to Use Form Load and Button click Event in C#
- How to use Advanced Filter DataGridView in C#
- How to use TagListControl in C#
- How to use Error Provider in C#
- How to Drag and Drop controls in C#
- How to Create a Random Password Generator in C#
- How to make an Application auto run on Windows startup in C#
- How to Create a Wait Form Dialog in C#
Categories
Popular Posts
C# Tutorial
07/20/2024
How to Download Microsoft SQL Server
06/22/2024
What Are RESTful Web Services?
02/19/2024
What is ARM architecture?
04/01/2024