I have tried the following code but it throws exception "No value given for one or more required parameters".
protected void Button2_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select count(*) from quant_level1";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
while (i <= count)
{
string cmdstr = "select * from quant_level1 where id = i";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
con1.Close();
}
One mistake is within the select Statement:
You are trying to select an ID which you don't provide.
string cmdstr = "select * from quant_level1 where id = i";
Your select statement should look like:
string cmdstr = "select * from quant_level1 where id = " + i;
Your Loop-counter is/was within your string. It won't be replaced automatically.
try this -
work only if you are using Web Application
protected void Button2_Click(object sender, EventArgs e)
{
int i;
if (ViewState["count"] != null)
i = Convert.ToInt32(ViewState["count"].ToString());
else
i = 2; // assuming that it is your starting point as given in question
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select count(*) from quant_level1";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int)com1.ExecuteScalar();
if (i < count)
{
string cmdstr = "select * from quant_level1 where id = i";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
ViewState["count"] = i.ToString();
}
con1.Close();
}
This will do the trick in your case. happy coding :)
Since you want to fetch next row every time on clicking the button.
int i=2;
protected void Button2_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select * from quant_level1 where id ="+i;
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
if(reader.Read())
{
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
i++;
}
con1.Close();
}
Related
I'm working in Visual Studio 2019 In c
I have problem with updating data to database
I use local Visual Studio SQL database
private void button1_Click(object sender, EventArgs e)
{
String source = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
con.Open();
String sqlSelectQuery = "SELECT * FROM [Table] WHERE ID = "+ int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Kor"].ToString());
label4.Text = (dr["Kor"].ToString());
label5.Text = (dr["Kor"].ToString());
int s = 11;
string y = (dr["Kor"].ToString());
label4.Text = (dr["Kor"].ToString());
x = Int32.Parse(label4.Text);
x = x + 0;
label6.Text = (x.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
String source = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
con.Open();
x = x + 1;
label6.Text = (x.ToString());
String st = "UPDATE supplier SET Kor = " + label6.Text + " WHERE Id = " + textBox1.Text;
}
Add these lines
SqlCommand cmd = new SqlCommand(st, con);
int result = cmd.ExecuteNonQuery();
Please put a breakpoint and check the value of st, is it generating the valid query.
I would suggest to use parameterized query to avoid sql injection.
Also, please avoid using Select *, please use columns.
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();
}
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.
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);