Binding DatagridView to DataTable Snippets

String strConn = “Server = .\\sqlexpress;Database = NorthWind;Integrated Security = SSPI;”;

dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

conn = new SqlConnection(strConn);

da = new SqlDataAdapter(“Select Categories.CategoryName, Products.ProductName, Products.UnitPrice From Categories Inner Join Products on Products.CategoryID = Categories.CategoryID”, conn);

SqlCommandBuilder cmd = new SqlCommandBuilder(da);

ds = new DataSet();

da.Fill(ds, “Categories”);

bs = new BindingSource(ds, “Categories”);

dataGridView1.DataSource = bs;

bindingNavigator1.BindingSource = bs;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace CSharpBindingSource
{
public partial class Form1 : Form
{
SqlDataAdapter da;
SqlConnection conn;
DataSet ds;
BindingSource bs;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
String strConn = “Server = .;Database = NorthWind;Integrated Security = SSPI;”;

conn = new SqlConnection(strConn);
da = new SqlDataAdapter(“Select * From Employees”, conn);
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
ds = new DataSet();

da.Fill(ds, “Employees”);
bs = new BindingSource(ds, “Employees”);
dataGridView1.DataSource = bs;
bindingNavigator1.BindingSource = bs;
}

private void toolStripButton1_Click(object sender, EventArgs e)
{
bs.EndEdit();
da.Update(ds, “Employees”);
}
}
}

One response to this post.

  1. […] Binding DatagridView to DataTable Snippets July 2007 3 […]

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: