I am importing an Excel sheet into a SQL Server database. The Excel sheet contains 3 columns
id|data|passport
I am using SqlBulkCopy
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
string[] filePaths = null;
string strFileType = null;
string strFileName = null;
string strNewPath = null;
int fileSize;
int flag=0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
fileSize = FileUpload1.PostedFile.ContentLength / 1024;
//EXCEL DETAILS TABLE
con.Open();
//=========================================
DataTable dt8 = new DataTable();
SqlCommand cmd8 = new SqlCommand("insert into exceldetails (name,type,details,size)" + "values(#name,#type,#details,#size)", con);
cmd8.Parameters.Add("#name", SqlDbType.VarChar).Value = strFileName;
cmd8.Parameters.Add("#type", SqlDbType.VarChar).Value = strFileType;
cmd8.Parameters.Add("#details", SqlDbType.VarChar).Value = DateTime.Now;
cmd8.Parameters.Add("#size", SqlDbType.Int).Value = fileSize;
cmd8.ExecuteNonQuery();
con.Close();
try
{
SqlDataAdapter da8 = new SqlDataAdapter(cmd8);
da8.Fill(dt8);
}
catch { }
//=========================================
//CHOOSING EXCEL CONNECTIONSTRING
string excelConnectionString = "";
switch (strFileType)
{
case ".xls":
excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 8.0;");
break;
case ".xlsx":
{
excelConnectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 12.0 Xml;");
break;
}
}
//===================================
//PRE EXCEL COUNT
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand("Select ID,Data,passport FROM [Sheet1$]", connection);
OleDbCommand command1 = new OleDbCommand("select count(*) from [Sheet1$]", connection);
//Sql Server Table DataTable
DataTable dt4 = new DataTable();
SqlCommand cmd4 = new SqlCommand("select * from excelsheet", con);
try
{
SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
da4.Fill(dt4);//sql table datatable
}
catch { }
//===============================
//excelsheet datatable
DataTable oltlb = new DataTable();
OleDbCommand olcmd = new OleDbCommand("select * from [Sheet1$]", connection);
try
{
OleDbDataAdapter olda = new OleDbDataAdapter(olcmd);
olda.Fill(oltlb); //excel table datatable
}
catch { }
//==============================
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt7 = new DataTable();
dt7.Load(dr);
DataRow[] ExcelRows = new DataRow[dt7.Rows.Count];
DataColumn[] ExcelColumn = new DataColumn[dt7.Columns.Count];
//=================================================
for (int i1 = 0; i1 < ExcelRows.Length; i1++)
{
string a = ExcelRows[i1]["passport"].ToString();
char a1 = a[0];
if (a1 >= 'A' || a1 <= 'Z')
{
Label12.Text = "CAPITAL";
break;
}
else
{
Label12.Text = "notgood";
flag = flag + 1;
}
}
//=========================================================
if (flag == 0)
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
dt7.Rows.CopyTo(ExcelRows, 0);
//==========================================================================================
for (int i = 0; i < ExcelRows.Length; i++)
{
if (ExcelRows[i]["passport"] == DBNull.Value)
{
ExcelRows[i]["passport"] = 0;
}
}
bulkCopy.WriteToServer(ExcelRows);
//==========================================================================================
for (int i = 0; i < ExcelRows.Length; i++)
{
if (ExcelRows[i]["data"] == DBNull.Value)
{
// Include any actions to perform if there is no date
//ExcelRows[i]["data"] = Convert.ToDateTime("0");
}
else
{
DateTime oldDate = Convert.ToDateTime(ExcelRows[i]["data"]).Date;
DateTime newDate = Convert.ToDateTime(oldDate).Date;
ExcelRows[i]["data"] = newDate.ToString("yyyy/MM/dd");
}
}
//==========================================================================================
}
//======
}
else
{
Label13.Text = "Wrong Format";
}
}
}
}
}
ERROR AT :
string a = ExcelRows[i1]["passport"].ToString();
ERROR:
Object reference not set to an instance of an object.
Related
I an trying to do a simple task of reading from one table "tab2" in a database->save to xml and then reload it into table "tab1" both have the same structure, I asked previously and received the following code as an answer.
I am having problems I am now getting the database filed ONCE per item but with a date time stamp I don't think its writing the XML from reading the database properly I am running it twice to get the schema and once for data.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.accdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
//Conn.Close();//severl times connection has been open
Conn.Open();
DataSet ds = new DataSet();
ds.ReadXml(#"c:\\temp\\tab2.xml");
OleDbCommand cmd = new OleDbCommand();
//OleDbCommand cmd1 = new OleDbCommand();
DataTable dtCSV = new DataTable();
dtCSV = ds.Tables[0];
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
//cmd1.Connection = Conn;
for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
{
//for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
//{
// //cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
//}
cmd.Parameters.Clear();
if (dtCSV.Columns.Count > 1)
{
//command.Parameters.Add(new OleDbParameter("#EMPID", Convert.Tostring(empsplitIt[1])));
//cmd.Parameters.Add(dtCSV.Rows[row][0]);
cmd.Parameters.Add(new OleDbParameter("#Field1", Convert.ToString(dtCSV.Rows[row][0])));
cmd.Parameters.Add(new OleDbParameter("#dtCSV", Convert.ToString(dtCSV.Rows[row][1])));
cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (? , ?)");
cmd.ExecuteNonQuery();
}
}
//Conn.Close();
}
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
string strSql = "Select * from Table1"; //only launch in main
richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";
try
{
OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\\temp\\names.mdb; Persist Security Info = False");
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "fname,sname");
// Extract data set to XML file
ds.WriteXml(#"c:\\temp\\tab2.xml", XmlWriteMode.WriteSchema);
ds.WriteXml(#"c:\\temp\\tab2.xml");
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
}
}
}
I find from my code that there is two different connection strings with in it when I putin the corect spelling correcting these it now fails on the line
dtCSV = ds.Tables[0];
with this
Error System.IndexOutOfRangeException: Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
at WindowsFormsApp8.Form1.button1_Click(Object sender, EventArgs e) in
Code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
//Conn.Close();//severl times connection has been open
Conn.Open();
DataSet ds = new DataSet();
ds.ReadXml(#"c:\\temp\\tabel2.xml");
OleDbCommand cmd = new OleDbCommand();
//OleDbCommand cmd1 = new OleDbCommand();
DataTable dtCSV = new DataTable("tabel1");
dtCSV = ds.Tables[0];
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
//cmd1.Connection = Conn;
for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
{
//for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
//{
// //cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
//}
cmd.Parameters.Clear();
if (dtCSV.Columns.Count > 1)
{
//command.Parameters.Add(new OleDbParameter("#EMPID", Convert.Tostring(empsplitIt[1])));
//cmd.Parameters.Add(dtCSV.Rows[row][0]);
cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[row][0])));
cmd.Parameters.Add(new OleDbParameter("#field2", Convert.ToString(dtCSV.Rows[row][1])));
cmd.CommandText = ("INSERT INTO tabel1 ( field1, field2) VALUES (? , ?)");
cmd.ExecuteNonQuery();
}
}
//Conn.Close();
}
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
string strSql = "Select * from tabel2"; //only launch in main
richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";
try
{
OleDbConnection con = new OleDbConnection(ConnString);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "fname,sname");
// Extract data set to XML file
ds.WriteXml(#"c:\\temp\\tabel2.xml", XmlWriteMode.WriteSchema);
ds.WriteXml(#"c:\ \temp\\tabel2.xml");
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
}
}
}
I have looked at several posts already on trying to fix this issue and none of them are working.
I'm already using multiple active results.
I'm making sure to close the reader connections.
I'm using a different connection.
I'm using unique names for the reader, datatable, the reader, the command...
I am stuck.
The error is: There is already an open DataReader associated with this Command which must be closed first.
I have marked the error line with "*****error here *****".
Code:
protected void gridviewsched_RowDataBound(object sender, GridViewRowEventArgs e)
{
string nametime;
string name;
string time;
string initid;
string timeinitid = null;
GridView gridviewschedsub = (GridView)e.Row.FindControl("gridviewschedsub");
GridView gridviewschedcplt = (GridView)e.Row.FindControl("gridviewschedcplt");
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Public\\public website\\slDataBase.mdf;Integrated Security=True;Trusted_Connection=True; MultipleActiveResultSets=True;"))
{
con.Open();
DataTable dz = new DataTable();
dz.Columns.Add("age");
dz.Columns.Add("sex");
dz.Columns.Add("address");
if (e.Row.RowType == DataControlRowType.DataRow)
{
string id = gridviewsched.DataKeys[e.Row.RowIndex].Value.ToString();
using (var cmd = new SqlCommand("SELECT age,sex,address FROM precordTable WHERE Id='" + id + "'", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
//List<string> namedatelist = new List<string>();
while (reader.Read())
{
DataRow dr = dz.NewRow();
dr["age"] = reader[0].ToString();
dr["sex"] = reader[1].ToString();
dr["address"] = reader[2].ToString();
dz.Rows.Add(dr);
}
reader.Close();
}
gridviewschedsub.DataSource = dz;
gridviewschedsub.DataBind();
con.Close();
}
using (var cmd3 = new SqlCommand("SELECT name, initid FROM precordTable WHERE Id='" + id + "'", con))
{
con.Open();
using (SqlDataReader reader = cmd3.ExecuteReader())
{
List<string> namedatelist = new List<string>();
while (reader.Read())
{
name = reader["name"].ToString();
initid = reader["initid"].ToString();
time = DateTime.Now.ToString("MM-dd-yyyy");
time = Regex.Replace(time, "[^0-9a-zA-Z]+", "");
namedatelist.Add(name + time);
timeinitid = time + "$" + initid;
}
Session["timeinitid"] = timeinitid;
nametime = Regex.Replace(namedatelist[0].ToString(), "[^0-9a-zA-Z]+", "");
reader.Close();
}
}
var cmd2 = new SqlCommand("select case when exists((select * from [C:\\USERS\\PUBLIC\\PUBLIC WEBSITE\\SLDATABASE.MDF].INFORMATION_SCHEMA.tables where table_name = 'D" + timeinitid + "ou')) then 1 else 0 end", con);
if ((int)cmd2.ExecuteScalar() == 1)
{
string fQuery = "select item, scheduled from D" + timeinitid + "ou where 0 = 1";
string pQuery = "select item, scheduled from D" + timeinitid + "ou where initialed = '' and prescdr IS NULL and item != '';";
SqlDataAdapter sdyn = new SqlDataAdapter();
DataTable cpltTable = new DataTable();
cpltTable = GetData(pQuery);
gridviewschedcplt.DataSource = cpltTable;
gridviewschedcplt.DataBind();
con.Close();
}
else
{
return;
}
}
}
for (int j = 0; j < gridviewsched.Rows.Count; j++)
{
for (int i = 3; i < 9; i++)
{
gridviewsched.Rows[j].Cells[i].RowSpan = 2;
}
gridviewsched.Rows[j].Cells[2].RowSpan = 2;
}
}
private static DataTable GetData(string pQuery)
{
string schedtime;
string nowtime;
SqlDataAdapter sd1 = new SqlDataAdapter();
DataTable dTable = new DataTable();
using (SqlConnection conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Public\\public website\\slDataBase.mdf;Integrated Security=True;Trusted_Connection=True;MultipleActiveResultSets=True;"))
{
conn.Open();
SqlCommand cmd33 = new SqlCommand(pQuery, conn);
using (SqlDataReader reader99 = cmd33.ExecuteReader())
{
while (reader99.Read())
{
sd1.SelectCommand = cmd33;
***error here**** sd1.Fill(dTable);
DataRow newcpltTablerow = dTable.NewRow();
newcpltTablerow["item"] = reader99["item"].ToString();
dTable.Rows.Add(newcpltTablerow);
}
reader99.Close();
}
return dTable;
}
}
You do not need a SqlDataReader if you are using a SqldataAdapter. You are getting the error because you open a reader within an already open adapter. Do this instead (not compiled so tweak as needed and change the query to yours):
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
cmd33.ExecuteReader can only be called once. You are executing it for each row.
i have a problem in fetching value from data gridview. In the same event i am able to fetch value from datagrid view1 but in same event i am not able to fetch the value from datagridview2. Help me with correction in following code.
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(path);
SqlConnection con1 = new SqlConnection(path);
con.Open();
string selectSql = "select * from textbooks where class='" + txt_class.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(selectSql, con);
string textname = "";
tempcnt.Text = "test";
string bookname = "";
double bookquantity = 0;
string textname1 = "";
string bookname1 = "";
double stockquantity1 = 0;
double bookquantity1 = 0;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
bookname = (reader["name"].ToString());
bookquantity = Convert.ToInt32(reader["quantity"]);
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
textname = Convert.ToString(dataGridView1.Rows[i].Cells[0].Value);
if (textname == bookname)
{
bookquantity = bookquantity - 1;
temp_count.Text = bookquantity.ToString();
con1.Open();
string uquery = "update textbooks set quantity=" + bookquantity + " where name='" + bookname + "'";
SqlCommand cmd1 = new SqlCommand(uquery, con1);
cmd1.ExecuteNonQuery();
con1.Close();
}
}
}
}
con.Close();
con.Open();
string selectSql2 = "select * from notebooks";
SqlCommand cmd2 = new SqlCommand(selectSql2, con);
tempcnt.Text = "test";
using (SqlDataReader reader1 = cmd2.ExecuteReader())
{
while (reader1.Read())
{
bookname1 = (reader1["name"].ToString());
stockquantity1 = Convert.ToInt32(reader1["quantity"]);
tempcnt.Text = bookname1;
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
textname1 = dataGridView2.Rows[i].Cells[0].Value as string;
string temp = Convert.ToString(dataGridView2.Rows[i].Cells[0].Value);
tempcnt.Text = temp;
if (temp == bookname1)
{
tempcnt.Text = "success";
}
}
}
}
con.Close();
}
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
//matching columns
//SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
//SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
I know I need to add something like:
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
but I am not sure where I am supposed to add it in the above code
The column mappings are to be added to the bulkCopy.ColumnsMappings collection:
var mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
bulkCopy.ColumnMappings.Add(mapping1);
You do the mapping before you execute the WriteToServer call.
The MSDN documentation of SqlBulkCopyColumnMapping has further documentation and an example.
I am able to import excel sheet data into sql server table but i am unable to implement column mapping. please help.
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
bulkCopy.WriteToServer(dr);
con.Open();
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
con.Close();
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try { SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
Error:
No value given for one or more required parameters.
You created but didn't add the mappings to SqlBulkCopy.
Add the code below:
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);