Windows Forms: How to Load selected columns data in DataGridView in C#
By FoxLearn 7/29/2017 4:20:58 PM 4.98K
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
- Windows Forms: Text to speech in C#
- Windows Forms: Print Picture Box in C#
- Windows Forms: Advanced Filter DataGridView in C#
- Windows Forms: Progress Bar in C#
- How to create a Lucky Draw games in C#
- Windows Forms: Youtube Search with Paging in C#
- Windows Forms: How to Create a Random Password Generator in C#
- Windows Forms: Tag Control in C#
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024
How to use Factory Method Pattern in C#
02/16/2024