using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; public class Form1 : System.Windows.Forms.Form{ private System.Windows.Forms.DataGrid dataGrid1; private System.Data.DataSet dataSet1; private System.ComponentModel.Container components = null; public Form1() { InitializeComponent(); } private void InitializeComponent(){ this.dataGrid1 = new System.Windows.Forms.DataGrid(); this.dataSet1 = new System.Data.DataSet(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).BeginInit(); this.SuspendLayout(); this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point(0, 0); this.dataGrid1.Name = "dataGrid1"; this.dataGrid1.Size = new System.Drawing.Size(400, 200); this.dataGrid1.TabIndex = 0; this.dataSet1.DataSetName = "NewDataSet"; this.dataSet1.Locale = new System.Globalization.CultureInfo("en-US"); this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(400, 196); this.Controls.Add(this.dataGrid1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).EndInit(); this.ResumeLayout(false); } [STAThread] static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI"; string qry1 = @"select * from employee "; string qry2 = @"select * from order"; string sql = qry1 + qry2; SqlConnection conn = new SqlConnection(connString); SqlDataAdapter da = new SqlDataAdapter(sql, conn); da.TableMappings.Add("Table", "employee"); da.TableMappings.Add("Table1", "order"); da.Fill(dataSet1); DataRelation dr = new DataRelation( "employeeorders", dataSet1.Tables[0].Columns["employeeid"], dataSet1.Tables[1].Columns["employeeid"] ); dataSet1.Relations.Add(dr); dataGrid1.SetDataBinding(dataSet1, "employees"); } }
Author: coder
DataGrid Update: edit a table by binding component
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.DataGrid dataGrid1; private System.Windows.Forms.Button buttonUpdate; private System.Data.DataSet dataSet1; private System.Data.SqlClient.SqlCommand sqlCommand1; private System.ComponentModel.Container components = null; private SqlCommandBuilder cb; private SqlDataAdapter da; public Form1() { InitializeComponent(); } private void InitializeComponent(){ this.dataGrid1 = new System.Windows.Forms.DataGrid(); this.buttonUpdate = new System.Windows.Forms.Button(); this.dataSet1 = new System.Data.DataSet(); this.sqlCommand1 = new System.Data.SqlClient.SqlCommand(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).BeginInit(); this.SuspendLayout(); this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point(8, 8); this.dataGrid1.Name = "dataGrid1"; this.dataGrid1.Size = new System.Drawing.Size(440, 208); this.dataGrid1.TabIndex = 0; this.buttonUpdate.Location = new System.Drawing.Point(191, 232); this.buttonUpdate.Name = "buttonUpdate"; this.buttonUpdate.TabIndex = 1; this.buttonUpdate.Text = "Update"; this.buttonUpdate.Click += new System.EventHandler(this.buttonUpdate_Click); this.dataSet1.DataSetName = "NewDataSet"; this.dataSet1.Locale = new System.Globalization.CultureInfo("en-US"); this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(456, 272); this.Controls.Add(this.buttonUpdate); this.Controls.Add(this.dataGrid1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).EndInit(); this.ResumeLayout(false); } static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e){ string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI"; string sql = @"select * from employee "; SqlConnection conn = new SqlConnection(connString); sqlCommand1 = new SqlCommand(sql, conn); da = new SqlDataAdapter(); da.SelectCommand = sqlCommand1; cb = new SqlCommandBuilder(da); da.Fill(dataSet1, "employee"); dataGrid1.SetDataBinding(dataSet1, "employee"); } private void buttonUpdate_Click(object sender, System.EventArgs e) { da.Update(dataSet1, "employee"); } }
Bind DataSet to DataGrid
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.DataGrid dataGrid1; private System.ComponentModel.Container components = null; public Form1() { InitializeComponent(); } private void InitializeComponent(){ this.dataGrid1 = new System.Windows.Forms.DataGrid(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); this.SuspendLayout(); this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point(8, 8); this.dataGrid1.Name = "dataGrid1"; this.dataGrid1.Size = new System.Drawing.Size(608, 256); this.dataGrid1.TabIndex = 0; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(624, 272); this.Controls.Add(this.dataGrid1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); this.ResumeLayout(false); } static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e){ string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI"; string sql = @"select * from employee"; SqlConnection conn = new SqlConnection(connString); SqlDataAdapter da = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); da.Fill(ds, "customers"); // Bind the data table to the data grid dataGrid1.SetDataBinding(ds, "customers"); } }
Read comma separated value into DataSet
using System;
using System.Data;
using System.IO;
class Class1{
static void Main(string[] args){
DataSet myDataSet = GetData();
foreach (DataColumn c in myDataSet.Tables[“TheData”].Columns){
Console.Write(“{0,-20}”,c.ColumnName);
}
Console.WriteLine();
foreach (DataRow r in myDataSet.Tables[“TheData”].Rows)
{
foreach (DataColumn c in myDataSet.Tables[“TheData”].Columns)
{
Console.Write(“{0,-20}”,r);
}
Console.WriteLine();
}
}
private static DataSet GetData(){
string strLine;
string[] strArray;
char[] charArray = new char[] {','};
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add(“TheData”);
FileStream aFile = new FileStream(“csv.txt”,FileMode.Open);
StreamReader sr = new StreamReader(aFile);
strLine = sr.ReadLine();
strArray = strLine.Split(charArray);
for(int x=0;x<=strArray.GetUpperBound(0);x++) { dt.Columns.Add(strArray[x].Trim()); } strLine = sr.ReadLine(); while(strLine != null) { strArray = strLine.Split(charArray); DataRow dr = dt.NewRow(); for(int i=0;i<=strArray.GetUpperBound(0);i++) { dr[i] = strArray[i].Trim(); } dt.Rows.Add(dr); strLine = sr.ReadLine(); } sr.Close(); return ds; } } // File: csv.txt /* 1,2,3,4 5,6,7,8 */ [/csharp]
This example will read a csv file into a dataset and save it back when you press button 1
//This example code is from eran.rivlis at gmail.com
DataTable dt = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
string conString = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:csv” +
@”;Extended Properties=””Text;HDR=No;FMT=Delimited”””;
OleDbConnection conn = new OleDbConnection(conString);
OleDbDataAdapter da = new OleDbDataAdapter(@”Select * from table1.csv”, conn);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
StringBuilder sbCSV = new StringBuilder();
int intColCount = dt.Columns.Count;
foreach (DataRowView dr in dt.DefaultView)
{
for (int x = 0; x < intColCount; x++)
{
sbCSV.Append(dr[x].ToString());
if ((x + 1) != intColCount)
{
sbCSV.Append(",");
}
}
sbCSV.Append("
");
}
using (StreamWriter sw = new StreamWriter(@"c:csv able1.csv"))
{
sw.Write(sbCSV.ToString());
}
}
[/csharp]
Create table through SqlConnection
using System; using System.Data; using System.Data.SqlClient; class CommandExampleCreateDb { static void Main() { SqlConnection thisConnection = new SqlConnection("server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI"); SqlCommand nonqueryCommand = thisConnection.CreateCommand(); try { thisConnection.Open(); nonqueryCommand.CommandText = "CREATE DATABASE MyDb"; Console.WriteLine(nonqueryCommand.CommandText); nonqueryCommand.ExecuteNonQuery(); Console.WriteLine("Database created, now switching"); thisConnection.ChangeDatabase("MyDb"); nonqueryCommand.CommandText = "CREATE TABLE MyJava2sTable (COL1 integer)"; Console.WriteLine(nonqueryCommand.CommandText); Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery()); nonqueryCommand.CommandText = "INSERT INTO MyJava2sTable VALUES (99)"; Console.WriteLine(nonqueryCommand.CommandText); Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery()); } catch (SqlException ex) { Console.WriteLine(ex.ToString()); } finally { thisConnection.Close(); Console.WriteLine("Connection Closed."); } } }
Use ExecuteNonQuery() to run DDL statements: create table
using System; using System.Data; using System.Data.SqlClient; class ExecuteDDL { public static void Main() { SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa"); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "CREATE TABLE MyPersons (" + " PersonID int CONSTRAINT PK_Persons PRIMARY KEY," + " FirstName nvarchar(15) NOT NULL," + " LastName nvarchar(15) NOT NULL," + " DateOfBirth datetime" + ")"; mySqlConnection.Open(); Console.WriteLine("Creating MyPersons table"); int result = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("mySqlCommand.ExecuteNonQuery() = " + result); mySqlCommand.CommandText = "ALTER TABLE MyPersons " + "ADD EmployerID nchar(5) CONSTRAINT FK_Persons_Customers " + "REFERENCES Customers(CustomerID)"; result = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("mySqlCommand.ExecuteNonQuery() = " + result); mySqlCommand.CommandText = "DROP TABLE MyPersons"; result = mySqlCommand.ExecuteNonQuery(); Console.WriteLine("mySqlCommand.ExecuteNonQuery() = " + result); mySqlConnection.Close(); } }