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

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;
// ...
}
}

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.";

WPF checkbox as button in code behind

I want my checkbox to be visible as button. Check-boxes are generated dynamically in code behind file using C#.
How can I do that?
private void loadItems()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "ConString";
con.Open();
SqlCommand cmd = new SqlCommand("Select ItemId,ItemName from ITEMS", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
iid = (dt.Rows[i]["ItemId"]).ToString();
iname = dt.Rows[i]["ItemName"].ToString();
CheckBox btn = new CheckBox();
btn.Content = iname;
btn.Height = 20;
btn.Width = 150;
btn.Tag = iname;
//var2 = btn.Tag.ToString();
wrapItems.Children.Add(btn);
btn.Click += new RoutedEventHandler(CheckBoxChecked);
//btn.RaiseEvent(new RoutedEventArgs(Button.btnClick(sender,e)));
con.Close();
}

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;

data insert an retrival to/from database using checked list box

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"]);
}

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