I got a stuck at line : string str = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
with error message : Object reference not set to an instance of an object
Please help me,
Thank everyone
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.IO;
using System.Data.OleDb;
using System.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
private string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string filePath = openFileDialog1.FileName;
string extension = Path.GetExtension(filePath);
string conString = "";
string sheetName = "";
switch (extension)
{
case ".xls":
conString = string.Format(Excel03ConString, filePath, "YES");
break;
case ".xlsx":
conString = string.Format(Excel07ConString, filePath, "YES");
break;
}
using (OleDbConnection con = new OleDbConnection(conString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dt.Rows[0]["Table_Name"].ToString();
con.Close();
}
}
using (OleDbConnection con = new OleDbConnection(conString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
OleDbDataAdapter oda = new OleDbDataAdapter();
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
DataTable dt = new DataTable();
oda.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[1]
{
new DataColumn("Email", typeof(string))
});
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string Email = row.Cells[0].Value.ToString();
dt.Rows.Add(Email);
}
if (dt.Rows.Count > 0)
{
string str = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(str))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
sqlBulkCopy.DestinationTableName = "dbo.DataTemp";
sqlBulkCopy.ColumnMappings.Add("Email", "Email");
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
}
}
}
}