data insert an retrival to/from database using checked list box - c#-4.0

How to insert and retrieve data to/from database using checkedlistbox in c#
here is my cod eon button click event :
string CS = ConfigurationManager.ConnectionStrings["RosterFinal"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
var Sep = "";
string INSERTq = "insert into T_Entity values(#Tno,#Tname,#STime,#ETime,#Skill1,#S_Day1)";
SqlCommand cmd = new SqlCommand(INSERTq, con);
cmd.Parameters.AddWithValue("#Tno", txtTNo.Text);
cmd.Parameters.AddWithValue("#Tname", txtTNa.Text);
cmd.Parameters.AddWithValue("#STime", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#ETime", dateTimePicker2.Text);
foreach (object i in checkedListBox1.CheckedItems )
{
// cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Skill1", checkedListBox1.SelectedItem.ToString());
}
foreach (object m in cbDay.CheckedItems)
{
// cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#S_Day1", cbDay.SelectedItem.ToString());
}
con.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
It is not readind the scaller parameters and givein exception that scaller parameters skill1 must be unique

This exception is because of setting parameters "#Skill1" and "#S_Day1" multiple times for a single insert statement.
Also, in foreach loop, you are setting the same value each time, that's of no use.
I suggest you to use following code,
using (SqlConnection con = new SqlConnection(CS))
{
var Sep = "";
string INSERTq = "insert into T_Entity values(#Tno,#Tname,#STime,#ETime,#Skill1,#S_Day1)";
SqlCommand cmd = new SqlCommand(INSERTq, con);
cmd.Parameters.AddWithValue("#Tno", txtTNo.Text);
cmd.Parameters.AddWithValue("#Tname", txtTNa.Text);
cmd.Parameters.AddWithValue("#STime", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#ETime", dateTimePicker2.Text);
cmd.Parameters.AddWithValue("#Skill1", checkedListBox1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#S_Day1", cbDay.SelectedItem.ToString());
con.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}

I think this may help u..
compare this code and modify as urs..
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
string query = "select employee_id,Employee_name from employee_details order by employee_name";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataAdapter sda ;
DataSet ds = new DataSet();
sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow datarow in dt.Rows)
{
checkedListBox1.Items.Add(datarow["employee_id"] + ": " + datarow["Employee_name"]);
}

Related

New to SQL - Need to search more than 1 column but can't seem to get it to work with the AND OR coding

The below is the code for the single ID Column search. Can someone help me rewrite this to search other columns in the table please. I need to add LastName, Rank, and EmployerID as searchable as well:
string find = "select * from SDEmployee where (Id like '%' +#Id+ '%')";
SqlCommand cmd = new SqlCommand(find, con);
cmd.Parameters.Add("#Id", SqlDbType.NVarChar).Value = TextBox16.Text;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "Id");
GridView1.DataSourceID = null;
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
Label1.Text = "Data has been found.";
I tried using the Where, AND OR lines but maybe did not write them correctly. Not sure. I am thinking this might work but need some new eyes in it to check my thinking:
string find = "select * from SDEmployee where (Id like '%' +#Id+ '%' AND 2ndColumn like #var2)";
SqlCommand cmd = new SqlCommand(find, con);
cmd.Parameters.Add("#Id", SqlDbType.NVarChar).Value = TextBox16.Text;
cmd.Parameters.Add(#var2, SqlDbType.NVarChar).Value = TextBoxVar2.Text
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "Id");
GridView1.DataSourceID = null;
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
Label1.Text = "Data has been found.";

Load data into multiple excel sheets depending on conditions dynamically

I have a situation please help me out. I have to create multiple sheet in one excel file with different queries. Like i have to check if the particular column is null then the record against this query should be in excel file in new sheet and i have to check another column with other name if it is null or empty and then create a sheet for it and sheet should be created only if the query returns some result otherwise there should not be any empty sheet. i have 8 different columns to check .
For Example I have to execute following query which will be in source
SELECT DISTINCT AgencySourceSystemCode,SourceAgencyID,ProgramCode,PolicyNumber,EffectiveDate,AgencyName
FROM POL.vw_PolicyPremiumData
WHERE AgencyName IS NULL OR AgencyName = ''
And Sample result is
AgencySourceSystemCode SourceAgencyID
ProgramCode PolicyNumber
EffectiveDate AgencyName
GEN 1050- CAB DN17000008
2010-06-10 NULL
GEN 1050- CAB DN17000008
2011-06-10 NULL
GEN 1050- CAB DN17000008
2012-06-10 NULL
GEN 1050- CAB DN17000010
2010-06-10 NULL
GEN 1050- CAB DN17000010
2012-06-10 NULL
GEN 1050- CAB DN17000012
2010-06-22 NULL
GEN 1050- CAB DN17000012
2011-06-22 NULL
Here Agency Name is NULL like this i will have source query where Effective can be null .
I used this code snippet to create dynamic Excel file sheets .
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace ST_db9b6187d17c4dc99314d6ccb6ee7b08
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
string query = string.Empty;
string FileName = string.Empty;
string TableName = string.Empty;
string connstring = string.Empty;
string FolderPath = string.Empty;
string where = string.Empty;
string PackageName = "Error";
int SourceId = 0;
int BatchId = 0;
int flag = 0;
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
FolderPath = Dts.Variables["$Package::TempFolderPath"].Value.ToString();
FolderPath = FolderPath+"\\";
//if (FolderPath.LastIndexOf("\\")="\\")
//{
// FolderPath = Dts.Variables["$Package::TempFolderPath"].Value.ToString();
//}
if (File.Exists(FolderPath + PackageName + "File.XLSX"))
{
File.Delete(FolderPath + PackageName + "File.XLSX");
}
if (FolderPath.Contains(".xlsx"))
{
FolderPath = FolderPath.Trim('\\');
FolderPath = FolderPath.Remove(FolderPath.LastIndexOf('\\') + 1);
}
//USE ADO.NET Connection from SSIS Package to get data from table
string con = Dts.Connections["oledb_conn"].ConnectionString.ToString();
OleDbConnection _connection = new OleDbConnection(con);
OleDbCommand cmd = new OleDbCommand();
//Read distinct error euerries
query = "select distinct ErrorQuery, SheetName from ErrorMapping where FileType = 'PremiumFile'";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
cmd.CommandText = query;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorMapping = new DataTable();
dt_ErrorMapping.Load(cmd.ExecuteReader());
_connection.Close();
if (dt_ErrorMapping != null && dt_ErrorMapping.Rows.Count > 0)
{
foreach (DataRow dt_ErrorMapping_row in dt_ErrorMapping.Rows)
{
query = dt_ErrorMapping_row["ErrorQuery"].ToString();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.CommandTimeout = 0;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorInfo = new DataTable();
dt_ErrorInfo.Load(cmd.ExecuteReader());
_connection.Close();
if (dt_ErrorInfo != null && dt_ErrorInfo.Rows.Count > 0)
{
Error(dt_ErrorMapping_row["SheetName"].ToString());
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::TempFolderPath"].Value.ToString() + "\\" +
"Error" + datetime + ".log"))
{
sw.WriteLine("Error Message: " + exception.Message.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
public void ExportExcelFile(DataSet ds, string connstring, string SheetName)
{
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Cmd.CommandTimeout = 0;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table [" + SheetName + "] (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
Excel_OLE_Con.Close();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
bool firstRow = true;
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into [" + SheetName + "] (" + sqlCommandValue + ") VALUES(";
int columnCount = table.Columns.Count;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.CommandTimeout = 0;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i].ToString() + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
Excel_OLE_Con.Close();
}
}
public void Error(string ActualSheetName)
{
//USE ADO.NET Connection from SSIS Package to get data from table
string con = Dts.Connections["oledb_conn"].ConnectionString.ToString();
OleDbConnection _connection = new OleDbConnection(con);
OleDbCommand cmd = new OleDbCommand();
//drop Excel file if exists
if (!string.IsNullOrEmpty(ActualSheetName))
{
//FileType='PremiumFile'"
query = "Select ErrorQuery,SheetName,FileType from pol.ErrorMapping Where SheetName = '" + ActualSheetName + "' and FileType='PremiumFile'";
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.CommandTimeout = 0;
cmd.Connection = _connection;
_connection.Open();
DataTable dt_ErrorInfo = new DataTable();
dt_ErrorInfo.Load(cmd.ExecuteReader());
//cmd.ExecuteNonQuery();
_connection.Close();
if (dt_ErrorInfo != null && dt_ErrorInfo.Rows.Count > 0)
{
foreach (DataRow dt_ErrorInfo_row in dt_ErrorInfo.Rows)
{
query = dt_ErrorInfo_row["ErrorQuery"].ToString();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
//cmd.CommandTimeout = 600;
cmd.Connection = _connection;
cmd.CommandTimeout = 0;
_connection.Open();
DataTable dt_Actual_data = new DataTable();
dt_Actual_data.Load(cmd.ExecuteReader());
//cmd.ExecuteNonQuery();
_connection.Close();
FileName = PackageName + dt_ErrorInfo_row["FileType"].ToString();
//TableName = "ErrorFileInfo ";
//Construct ConnectionString for Excel
connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + FileName + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
string SheetName = "";
object[] array = dt_ErrorInfo_row.ItemArray;
SheetName = array[1].ToString();
//Load Data into DataTable from SQL ServerTable
//string queryString = "SELECT * from " + TableName + " ";
//OleDbDataAdapter adapter = new OleDbDataAdapter(query, _connection);
DataSet ds = new DataSet();
ds.Tables.Add(dt_Actual_data);
//adapter.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
ExportExcelFile(ds, connstring, SheetName);
flag++;
}
}
}
}
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}

Error in ExecuteNonQuery command in C#, can't update database

here is the code that i have written for change password in my website in C#, but it shows the error in "ExecuteNonQuery()" command..and i cant update the database with new password... i have tried many solution for that like i have check permission in windows authentication for modify the "Database" file..
-> Code in Change.aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb";
conn = new OleDbConnection(connectionString);
conn.Open();
string str1 = "select * from Student_Login where Password ='" + TextBox1.Text + "'";
OleDbCommand cmd = new OleDbCommand(str1, conn);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
OleDbConnection con1 = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb");
con1.Open();
string str = "UPDATE Student_Login SET Password=" + TextBox3.Text + "where Password= " + TextBox1.Text;
using (OleDbCommand cmd1 = new OleDbCommand(str, con1))
{
cmd1.ExecuteNonQuery();
}
Label1.Visible = true;
con1.Close();
}
else
{
Label3.Visible = true;
}
conn.Close();
}
...................
error image
It seems that there are a few syntax issues within your existing code, such as missing quotes around your parameter values when building your queries and concatenating your strings like the following line :
string str = "UPDATE Student_Login SET Password='" + TextBox3.Text + "' where Password= " + TextBox1.Text + "'";
A bigger issue here is that you aren't using SQL Parameterization, which can cause issues like this to occur (and lead to SQL Injection vulnerabilities). Consider the following code, which should resolve all of your previous issues and keep you protected against any injection-based nastiness:
// Create your connection
using (var conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb"))
{
// Build your first query
var query = "SELECT * FROM Student_Login WHERE Password = #password";
// Create a command to execute your query
using (var cmd = new OleDbCommand(query, conn))
{
// Open your connection
conn.Open();
// Add your parameter (prevents SQL Injection and syntax issues)
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
// Execute your query into a reader
using (var dr = cmd.ExecuteReader())
{
// Go through each row
while(dr.Read())
{
// Build an update query
var updateQuery = "UPDATE Student_LogIn SET Password = #password WHERE Password = #oldPassword";
// Build a new command to execute
using (var updateCmd = new OleDbCommand(updateQuery, conn))
{
// Set a parameter and execute
updateCmd.Parameters.AddWithValue("#password", TextBox3.Text);
updateCmd.Parameters.AddWithValue("#oldPassword", TextBox1.Text);
// Execute your query
updateCmd.ExecuteNonQuery();
Label1.Visible = true;
}
}
}
}
}
You can also try this version which doesn't rely on named parameters :
// Create your connection
using (var conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Lenovo\Desktop\PlacementCell\PlacementCell\Database.mdb"))
{
// Build your first query
var query = "SELECT * FROM Student_Login WHERE Password = ?";
// Create a command to execute your query
using (var cmd = new OleDbCommand(query, conn))
{
// Open your connection
conn.Open();
// Add your parameter (prevents SQL Injection and syntax issues)
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
// Execute your query into a reader
using (var dr = cmd.ExecuteReader())
{
// Go through each row
while(dr.Read())
{
// Build an update query
var updateQuery = "UPDATE Student_LogIn SET Password = ? WHERE Password = ?";
// Build a new command to execute
using (var updateCmd = new OleDbCommand(updateQuery, conn))
{
// Set a parameter and execute
updateCmd.Parameters.AddWithValue("#password", TextBox3.Text);
updateCmd.Parameters.AddWithValue("#oldPassword", TextBox1.Text);
// Execute your query
updateCmd.ExecuteNonQuery();
Label1.Visible = true;
}
}
}
}
}
Can you try once this...
updateCmd.Parameters.Add("#password", SqlDbType.VarChar);
updateCmd.Parameters["#password"].Value = TextBox3.Text;
updateCmd.Parameters.Add("#oldPassword", SqlDbType.VarChar);
updateCmd.Parameters["#oldPassword"].Value = TextBox1.Text;

invalid column name when my insert data is string,when i use int it works fine

When i replace EmerPacienti with PatientId it works fine, why happen that?
if (DropDownList3.SelectedItem.Value == "In-Pacient")
{
SqlDataAdapter Da = new SqlDataAdapter("select * from Ipacient where EmerPacienti=" + TextBox11.Text + "", cn);
//SqlCommandBuilder Cmd = new SqlCommandBuilder(Da);
DataSet Ds = new DataSet();
Da.Fill(Ds, "Ipacient");
GridView1.DataSource = Ds.Tables[0];
GridView1.DataBind();
Use sql parameters to prevent sql injection, then you also don't need to wrap it in apostrophes which is required on text columns. So this is much better:
using (var cn = new SqlConnection("insert connection string"))
using(var da = new SqlDataAdapter("select * from Ipacient where EmerPacienti=#EmerPacienti", cn))
{
da.SelectCommand.Parameters.Add("#EmerPacienti", SqlDbType.VarChar).Value = TextBox11.Text;
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
If it was an int-value use int.Parse/int.TryParse:
using (var cn = new SqlConnection("insert connection string"))
using(var da = new SqlDataAdapter("select * from Ipacient where PatientId=#PatientId", cn))
{
int patientId;
if (int.TryParse(TextBox11.Text, out patientId))
{
da.SelectCommand.Parameters.Add("#PatientId", SqlDbType.Int).Value = patientId;
// ...
}
}

Excel to dataTable

I need to fetch a sheet from excel to a datatable. I first tried with LinqToExcel library, but this fetched the large numbers from the excel sheet as exponential numbers. I'm talking about big numbers like "2352143523453452334544". Only if they are formated as text it would work ok.
After that i've tried this :
OleDbConnection con = null;
System.Data.DataTable dt = null;
System.Data.DataTable dataTable1 = new System.Data.DataTable();
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + UploadFileName + ";Extended Properties=Excel 8.0;";
string sql_xls;
con = new OleDbConnection(conStr);
con.Open();
//OracleDataAdapter oda = new OracleDataAdapter();
//OracleCommand cmd = new OracleCommand("select * from [Sheet1$]", con);
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string[] excelSheetNames = new string[dt.Rows.Count];
int i = 0;
foreach (System.Data.DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString(); i++;
}
sql_xls = "SELECT * FROM [" + excelSheetNames[0] + "]";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql_xls, conStr);
System.Data.DataSet myDataSet = new System.Data.DataSet();
dataAdapter.Fill(myDataSet, "ExcelInfo");
dataTable1 = myDataSet.Tables["ExcelInfo"];
This one returned the same values in the same conditions as null.
Isn't there a simple way to fetch data from a excel file as it is? No conversions, no nothing. Just take it all as a string, and put it into a datatable ?
This is what i used and it worked for me:
private DataTable LoadXLS(string strFile, String sheetName)
{
DataTable dtXLS = new DataTable(sheetName);
try
{
string strConnectionString = "";
if(strFile.Trim().EndsWith(".xlsx"))
{
strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
}
else if(strFile.Trim().EndsWith(".xls"))
{
strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
OleDbConnection SQLConn = new OleDbConnection(strConnectionString);
SQLConn.Open();
OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();
string sql = "SELECT * FROM [" + sheetName + "$]";
OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);
SQLAdapter.SelectCommand = selectCMD;
SQLAdapter.Fill(dtXLS);
SQLConn.Close();
}
catch (Exception)
{
throw;
}
return dtXLS;
}
But you can try to export to CSV as well:
LinqToCSV

Resources