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

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

Related

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

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

Fill:selectcommand.connction property has not been initialised

i am getting error on sda.Fill(dt); that Fill:selectcommand.connction property has not been initialised what could be a problem in connection?
protected void Updatecustomer(object sender, GridViewUpdateEventArgs e)
{
string cstid = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblcustomerid")).Text;
string csnm = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname")).Text;
string cmpn = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtcompany")).Text;
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\LENOVO\\Documents\\Visual Studio 2010\\WebSites\\LiveSms\\App_Data\\Sms.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update gridCompany set name=#name,company=#company where cid=#cid;
cmd.Parameters.Add("#cid", SqlDbType.NVarChar).Value = cstid;
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = csnm;
cmd.Parameters.Add("#comnpany", SqlDbType.NVarChar).Value = cmpn;
GridView1.EditIndex = -1;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}

retrieve data from access database

I want to retrieve a path of an image from access
DataTable myTable = new DataTable();
OleDbConnection myConnection = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = "SELECT ImageName AS 'ImageName', ImagePath AS 'Path' FROM [AImages] WHERE ID='" + _ID + "'";
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(myTable);
but in last line an error occurred like this: Data type mismatch in criteria expression.
I suspect the problem is with the way you pass an ID, maybe you can try this instead:
// note the ID=?
myCommand.CommandText = "SELECT ImageName AS 'ImageName', ImagePath AS 'Path' FROM [AImages] WHERE ID=?";
myCommand.CommandType = CommandType.Text;
// now a parameter
var pId = new OleDbParameter {Value = _ID};
myCommand.Parameters.Add(pId);
I hope this helps.

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