how we can export or import data from or to to Datagridview from Excel or Access file??
I need to know the code for export and import..any one help please
try this:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(#"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Net-informations.com");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
}
}
Here is another tutorial
or just use google
I'll try to extend previous post with Access sample:
DataTable LoadSchemaFromAccess(string szFilePath)
{
System.Data.OleDb.OleDbCommand cmd;
try
{
System.Data.OleDb.OleDbConnection cnn = new System.Data.OleDb.OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", szFilePath));
cnn.Open();
System.Data.DataTable schemaTable = cnn.GetSchema("Tables");
cnn.Close();
return schemaTable;
}
catch (exception e)
{
MessageBox.Show(e.Message);
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
}
}
string LoadDataFromAccess(string szTableName )
{
string GetData = L"SELECT * FROM " + szTableName;
System.Data.OleDb.OleDbCommand cmd;
string szColumns = "";
try
{
System.Data.OleDb.OleDbConnection cnn = new System.Data.OleDb.OleDbConnection
(string.Format(L"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", szPath));
cnn.Open();
System.Data.DataTable dt = new System.Data.DataTable();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = cnn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = GetData;
OleDbDataAdapter adt = new OleDbDataAdapter(cmd);
adt.SelectCommand = cmd;
adt.Fill(dt);
cnn.Close();
return dt;
}
catch (exception e)
{
MessageBox.Show(e.Message);
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
}
}
Hope this helped.
Related
I've been practicing with ADO.NET and SQL Server in a Windows Forms application, but I can't get table data into a DataGridView on the press of a button.
There are no errors and I make server connection checking. I have corresponding database and table name with some data in it.
Any ideas what I am doing wrong?
Here is code from the button:
private void button1_Click(object sender, EventArgs e)
{
string ConnectionString = "Server=DESKTOP-FV268LU;Database=ado_database;Integrated Security=true";
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = ConnectionString;
myConnection.Open();
if (myConnection.State == ConnectionState.Open)
label1.Text = "YES!";
else if (myConnection.State != ConnectionState.Open)
label1.Text = "Nope!!";
string sql = "SELECT * FROM Main";
SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection);
DataSet myDataSet = new DataSet("Main");
myAdapter.Fill(myDataSet, "Main");
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = myDataSet.DefaultViewManager;
dataGridView1.Refresh();
}
You need to call after setting the DataSource
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = myDataSet.DefaultViewManager;
dataGridView1.DataBind();
EDIT
dataGridView1.DataSource = myDataSet.Tables[0];
dataGridView1.AutoGenerateColumns = true;
How about this?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
private DataTable table;
private DAL dal;
protected void Form_Load(object sender, EventArgs e)
{
dal = new DAL();
table = dal.GetData();
dataGridView1.DataSource = table;
}
public Form1()
{
InitializeComponent();
}
private void button5_Click(object sender, EventArgs e)
{
dal.UpdateData(table);
}
class DAL //data access layer
{
string connString = #"Server=EXCEL-PC\EXCELDEVELOPER;Database=AdventureWorksLT2012;Trusted_Connection=True;";
SqlDataAdapter da;
SqlCommandBuilder builder;
DataTable table;
SqlConnection conn;
public DataTable GetData()
{
table = new DataTable("dataGridView1");
conn = new SqlConnection(connString);
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(#"SELECT * FROM [SalesLT].[Product]", conn);
builder = new SqlCommandBuilder(da);
da.Fill(table);
return table;
}
public void UpdateData(DataTable table)
{
if (da != null && builder != null)
{
da.Update(table);
}
}
}
}
}
Here is another option for you to consider.
private void button6_Click(object sender, EventArgs e)
{
SqlConnection con = new System.Data.SqlClient.SqlConnection();
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Server=EXCEL-PC\\EXCELDEVELOPER;Database=AdventureWorksLT2012;Trusted_Connection=True;";
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
for (int i = 0; i <= dataGridView1.Rows.Count - 2; i++)
{
String insertData = "INSERT INTO Import_List(Fname, Lname, Age) VALUES (#Fname, #Lname, #Age)";
SqlCommand cmd = new SqlCommand(insertData, con);
cmd.Parameters.AddWithValue("#Fname", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Lname", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Age", dataGridView1.Rows[i].Cells[2].Value);
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
}
I'm trying to fill a datagridview with SQL Server table data and I get an error:
ExecuteReader: Connection property has not been initialized.
How do I fix this ?
private void BlackListLoad()
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
BindingSource bs = new BindingSource();
var table = dt;
var connection =
#"Data Source=someone-someone\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (var con = new SqlConnection { ConnectionString = connection })
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.CommandText = #"SELECT * FROM [dbo].[Blacklist1]";
table.Load(cmd.ExecuteReader());
bs.DataSource = table;
ListGrid.ReadOnly = true;
ListGrid.DataSource = bs;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
You haven't given your SqlCommand a connection! As it states you need to do this. You can fix this by doing:
cmd.Connection = con; just before you execute the reader.
Read here for more information: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx
It also looks like you're not opening your connection, which can be fixed with:
con.Open();
With a new connection object, you do not need to check whether it's open, because it won't be.
Try it this way.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
}
}
This is what I have so far:
static void Main(string[] args)
{
DataTable t = new DataTable();
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
cnn = new SqlConnection(connetionString);
string sql = "SELECT * FROM shiplabels";
SqlDataAdapter a = new SqlDataAdapter(sql, cnn);
try
{
cnn.Open();
a.Fill(t);
cnn.Close();
}
catch (Exception ex)
{
Console.WriteLine ("Can not open connection ! ");
}
}
I want to connect to this Microsoft DB and pull data from it. I am having trouble just getting this to work! When I use this code datatable t has 0 rows where it should come back with a few hundred. I'm clearly missing something simple here?
DataTable dt = new DataTable();
SqlDataAdapter sqlAdtp = new SqlDataAdapter();
string connectionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
string sql = "SELECT * FROM shiplabels";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = CommandType.Text;
try
{
sqlAdtp.SelectCommand = cmd;
sqlAdtp.Fill(dt);
}
catch (Exception ex)
{
}
}
}
First, you don't need to open the connection when using SqlDataAdapter.
Also, you forgot the CommandType.
This should work fine for you.
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
adapter.Dispose();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
When I try to use the method GetCities(), it says:
Fill: SelectCommand.Connection property has not been initialized.
Can anyone please advise on what to do?
public class CitiesService
{
public DataSet DS;
public OleDbConnection myConnection;
public OleDbDataAdapter adapter;
public OleDbDataAdapter adapter2;
public CitiesService()
{
}
public DataSet GetCities()
{
OleDbCommand myCmd = new OleDbCommand("SPtblCities", myConnection);
myCmd.CommandType = CommandType.StoredProcedure;
OleDbDataAdapter Adapter = new OleDbDataAdapter();
Adapter.SelectCommand = myCmd;
DataSet dataSet = new DataSet();
try
{
Adapter.Fill(dataSet, "tblCities");
dataSet.Tables["tblCities"].PrimaryKey = new DataColumn[]
{
dataSet.Tables["tblCities"].Columns["CityID"]
};
}
catch (OleDbException ex)
{
throw ex;
}
return dataSet;
}
}
Yes, the connection was not initialized, it is null.
Replace
public OleDbConnection myConnection;
with
public OleDbConnection myConnection = new OleDbConnection(ConnectionString);
or in the method:
myConnection = new OleDbConnection(ConnectionString);
OleDbCommand myCmd = new OleDbCommand("SPtblCities", myConnection);
I would recommend you use this pattern and remember that some of these objects are disposable.
public class CitiesService
{
public DataSet DS;
public OleDbConnection myConnection;
public OleDbDataAdapter adapter;
public OleDbDataAdapter adapter2;
public CitiesService()
{
}
public DataSet GetCities()
{
using (DataSet dataSet = new DataSet())
{
using (OleDbConnection myConnection = new OleDbConnection(ConnectionString))
{
myConnection.Open();
using (OleDbCommand myCmd = myConnection.CreateCommand())
{
myCmd.CommandType = CommandType.StoredProcedure;
using (OleDbDataAdapter Adapter = new OleDbDataAdapter())
{
Adapter.SelectCommand = myCmd;
try
{
Adapter.Fill(dataSet, "tblCities");
dataSet.Tables["tblCities"].PrimaryKey = new DataColumn[] { dataSet.Tables["tblCities"].Columns["CityID"] };
}
catch (OleDbException ex)
{
throw ex;
}
}
}
myConnection.Close();
}
return dataSet;
}
}
}
I have used the following code for displaying names of my SQL db tables in a combo box.
Now I want that when I click on any of these table names from the combo box, my DGV populates with that table's contents.
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Then I used the following code for populating my DGV but it's not working; please help.
private void PopulateGridView()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedText;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
PopulateGridView(comboBox1.SelectedValue.ToString());
}
}
just try this:
update your code in the Form Load with below:
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "table_name";
comboBox1.ValueMember = "table_name";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
so basically you have added one extra line comboBox1.ValueMember = "table_name";
and make your PopulateGridView method like this:
private void PopulateGridView(string tblName)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + tblName;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
it has to work.
Also, I see, you are creating SqlConnection object everywhere, including SqlCommand and SqlDataAdapter.
try to wrap them up in static methods i.e.
- public static SqlConnection OpenConnection()
- public static DataTable ExecuteSelectQuery(string Query)
- public static bool ExecuteModifyQuery(string Query)
try to write as less amount of code as you can.
Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
string strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedValue;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}