I'm trying to implement date-picker functionality in my project, but I can't do it quite right. I'm trying to pass the date-picker value in my oracle string so that it will compare with my db column and return results on the date criteria...
Whenever I pass it to the select statement it won't generate errors particularly but on button click it doesn't perform anything except it shows "not connected".
str = "Select * from sania.doctor where APPOINTMENT_DATE = "+ datepicker1.value;
It is clear it is logical mistake but I'm new to this C# concepts I need someone to tell me how to pass it and then display the results as well.
private void button1_Click(object sender, EventArgs e)
try
{
OracleCommand com;
OracleDataAdapter oda;
string ConString = "Data Source=XE;User Id=system;Password=sania;";
OracleConnection con = new OracleConnection(ConString);
{
// string id = dateTimePicker1.Text.Trim();
con.Open();
// str = "Select * from sania.doctor where APPOINTMENT_DATE = " + dateTimePicker1.value;
str = "select * from sania.doctor where APPOINTMENT_DATE to_date('"+dateTimePicker1.Value.ToString("yyyyMMdd") + "', 'yyyymmdd')";
com = new OracleCommand(str);
oda = new OracleDataAdapter(com.CommandText, con);
dt = new DataTable();
oda.Fill(dt);
Rowcount = dt.Rows.Count;
//int val = 0;
for (int i = 0; i < Rowcount; i++)
{
dt.Rows[i]["APPOINTMENT_DATE"].ToString();
//if (id == dateTimePicker1.Value)// this LINE SHOWS ERROR--because it is a string and I am using date with it. Don't know conversion
// {
// val = 1;
//}
}
// if (val == 0)
// { MessageBox.Show("INVALID ID"); }
// else
// {
DataSet ds = new DataSet();
oda.Fill(ds);
if (ds.Tables.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
else { MessageBox.Show("NO RECORDS FOUND"); }
}
}
//}
catch (Exception)
{ MessageBox.Show("not connected"); }
}
Do not put values into SQL directly, use bind variables/parametes instead. For Oracle:
// :prm_Appointment_Date bind variable declared within the query
String str =
#"select *
from sania.doctor
where Appointment_Date = :prm_Appointment_Date";
....
using(OracleCommand q = new OracleCommand(MyConnection)) {
q.CommandText = str;
// datepicker1.Value passed into :prm_Appointment_Date via parameter
q.Parameters.Add(":prm_Appointment_Date", datepicker1.Value);
...
}
Doing like that you can be safe from either SQL Injection or Format/Culture differences
Related
I am performing search operation based on id which is auto incremented when I enter id as 0 it is retrieving data which is having id 1.
This is the search method
public DataTable Search(int code=0)
{
SqlConnection con = sqlConnection;
String Query = "Select * from person" + (code > 0 ? " where code =" + code : "");
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(Query, con);
{
DataTable dataTable = new DataTable("Temp");
sqlDataAdapter.Fill(dataTable);
con.Close();
return dataTable;
}
}
This is search button code
private void btnSearch_Click(object sender, EventArgs e)
{
if(txtSearchCode.Text.Length>0)
{
DataTable dataTable = new SqlHelper().Search(int.Parse(txtSearchCode.Text));
if(dataTable.Rows.Count>0)
{
try
{
txtCode.Text = dataTable.Rows[0]["code"].ToString();
txtFirstname.Text = dataTable.Rows[0]["firstname"].ToString();
txtLastname.Text = dataTable.Rows[0]["lastname"].ToString();
var a = dataTable.Rows[0]["gender"].ToString() == "Male" ? rbnMale.Checked = true : rbnFemale.Checked = true;
txtMobile.Text = dataTable.Rows[0]["mobile"].ToString();
dtpDOB.Text = dataTable.Rows[0]["dob"].ToString();
txtAge.Text = dataTable.Rows[0]["age"].ToString();
chkStatus.Checked = dataTable.Rows[0]["status"].ToString() == "active"? true :false;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("No Data Found");
}
}
else
{
MessageBox.Show("Please Enter Code");
}
}
You are not sending a where class if your conditional expression code > 0 is not satisfied, which is why sql-server returns all rows from the table person. Then when you pick the first row from the datatable using dataTable.Rows[0] it picks the one with id 1.
A better and secure way is to use a parameterized query instead.
String Query = "Select * from person where code = #code";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(Query, con);
sqlDataAdapter.SelectCommand.Parameters.AddWithValue("#code",code);
When you use Code = 0; you actually are doing select * from table.
But in the btnSearch_Click handler you are always processing 0th Rows from the resultset.
txtCode.Text = dataTable.Rows[0]["code"].ToString(); <------ See this line you have [0] hardcoded
Possibly the record with id 1 is first record in your query Result Set.
Edit:
You need to Loop through dataTable.Rows[] array and capture/process each result.
I'm trying to Iterate through rows in a 2 column table to check 1 field in each row against a Name. Once found I want to code to assign the corresponding Number to the OurNumber variable, and break out of the loop by setting GotTheNumber to true.
Below is the code I'm using:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
DataTable table = new DataTable();
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
{
string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(table);
}
string SelectedName = DropBoxEmp.Text;
bool GotTheNumber = false;
int OurNumber = 0;
while (!GotTheNumber)
{
foreach (DataRow ThisRow in table.Rows)
{
if (SelectedName = (table.Rows[ThisRow]))
{
OurNumber = ///THATNUMBER///;
GotTheNumber = true;
}
}
}
MessageBox.Show(SelectedName);
var GoodNumber = (table.Rows[OurNumber]["PayrollNo"].ToString());
form.PassValueName = SelectedName;
form.PassSelectedPayroll = GoodNumber;
form.Tag = this;
form.Show(this);
Hide();
}
I don't know where to go from the If statement, so any help would be greatly appreciated.
Looping through the rows in your client program is exactly what you don't want to do. Let the database do that work for you. Try this:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
object result;
string query = "SELECT PayrollNo FROM [Employee] WHERE FirstName + ' ' + LastName = ?";
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
//guessing at type and length here
cmd.Parameters.Add("?", OleDbType.VarWChar, 50).Value = DropBoxEmp.Text;
conn.Open();
result = cmd.ExecuteScalar();
}
if (result != null && result != DBNull.Value)
{
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
form.PassValueName = DropBoxEmp.Text;
form.PassSelectedPayroll = (int)result;
form.Tag = this;
form.Show(this);
Hide();
}
}
If you really want to loop through the rows against all reason (it's slower, requires writing more code, and it's more error-prone), you can do this:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
DataTable table = new DataTable();
string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]";
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
{
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(table);
}
int PayrollNumber = 0;
foreach (DataRow ThisRow in table.Rows)
{
if (DropBoxEmp.Text == ThisRow["NAME"])
{
PayrollNumber = (int)ThisRow["PayrollNo"];
break;
}
}
//the whole loop could also be consolidated to this:
//PayrollNumber = (int)table.Rows.First(r => r["NAME"] == DropBoxEmp.Text)["PayrollNo"];
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
form.PassValueName = DropBoxEmp.Text;
form.PassSelectedPayroll = PayrollNumber ;
form.Tag = this;
form.Show(this);
Hide();
}
Hm, hard to guess what exactly your problem is. But I think you just want to get the PayrollNo from the current row, aren't you?
Regarding the line further down ...
var GoodNumber = (table.Rows[OurNumber]["PayrollNo"].ToString());
... I think you could just call:
if (...)
{
OurNumber = ThisRow["PayrollNo"].ToString();
GotTheNumber = true;
}
However, I have no clue what you are doing with the following if-condition and if this really does what you want it to do:
if (SelectedName = (table.Rows[ThisRow]))
{
...
}
The first one is funtion that i call. second one is the code to show the data that has already been stored in database. Now when i input the license number from the txtno and select the License number from combobox cbonumber and press the btnsearch, there is no record found message is shown even though the licensenumber and numbertype exists is database
function
public DataTable CheckExistingLicenseNo(string LicenseNumber, string Numbertype)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=tprojectDB;");
string sql = "select *from tblDDDDDriver where LicenseNumber=#LicenseNumber and Numbertype=#Numbertype";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#LicenseNumber", LicenseNumber);
cmd.Parameters.AddWithValue("#Numbertype", Numbertype);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable db = new DataTable();
da.Fill(db);
return db; ;
}
code in btnsearch
private void btnsearch_Click(object sender, EventArgs e)
{
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.Text);
if (db.Rows.Count > 0)
{
if (cbonumbertype.Text == "LicenseNumber")
{
txtlicenseno.Text = db.Rows[0]["LicenseNumber"].ToString();
txtlicensecategory.Text = db.Rows[0]["LicenseCategory"].ToString();
txtissuedate.Text = db.Rows[0]["IssueDate"].ToString();
txtrenewdate.Text = db.Rows[0]["RenewDate"].ToString();
txtfullname.Text = db.Rows[0]["FullName"].ToString();
txtdob.Text = db.Rows[0]["DOB"].ToString();
txtaddress.Text = db.Rows[0]["Address"].ToString();
string gender = db.Rows[0]["Gender"].ToString();
if (gender == "Male")
{
txtgender.Text = " MALE";
}
else
{
txtgender.Text = "FEMALE";
}
txtvehicleno.Text = db.Rows[0]["VehicleNumber"].ToString();
txthealthstaus.Text = db.Rows[0]["HealthStatus"].ToString();
txtdrivertype.Text = db.Rows[0]["DriverType"].ToString();
Image img;
byte[] bytimg = (byte[])db.Rows[0]["Image"];
//convert byte of imagedate to Image format
using (MemoryStream ms = new MemoryStream(bytimg, 0, bytimg.Length))
{
ms.Write(bytimg, 0, bytimg.Length);
img = Image.FromStream(ms, true);
pictureBox1.Image = img;
}
}
DataTable dd = dc.GetMaxDeathNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dd.Rows.Count > 0)
{
txtdeathaccidentno.Text = dd.Rows[0]["DeathNumber"].ToString();
}
DataTable dM = dc.GetMaxMajorNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dM.Rows.Count > 0)
{
txtmajoraccidentno.Text = dM.Rows[0]["MajorNumber"].ToString();
}
DataTable dm = dc.GetMaxMinorNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dm.Rows.Count > 0)
{
txtminoraccidentno.Text = dm.Rows[0]["MinorNumber"].ToString();
}
DataTable dtrb = dc.GetTrafficRuleBroken(Convert.ToDecimal(txtlicensenumber.Text));
{
dataGridView1.DataSource = dtrb;
}
}
else
{
MessageBox.Show("No RECORD IS FOUND");
}
}
}
The only thing I suspect can be causing an issue is the value of cbonumbertype.Text. Change to cbonumbertype.SelectedValue and see if that wont help.
Change
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.Text);
To
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.SelectedValue);
I suspect that Bayeni's solution is the right one. You are possibly entering the ComboBox SelectedItem.Text value instead of the SelectedItem.Value value.
The easiest way to check this is to add a breakpoint to this line:
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.Text);
In Visual Studio, select Debug > Start Debugging and check if the value in cbonumbertype.Text is the one that you expect to see.
I have the following code which populates the Topic dropdownlist and saves it to a cached table:
bookingData2 = new DataTable();
DataTable DTable_List = new DataTable();
string connString = #"";
string query2 = #"Select * from [DB].dbo.[top]";// columng #1 = Specialty and column #2 = Topic
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query2, conn);
SqlDataAdapter da = new SqlDataAdapter(query2, conn);
da.Fill(bookingData2);
HttpContext.Current.Cache["cachedtable2"] = bookingData2;
bookingData2.DefaultView.Sort = "Topic ASC";
Topic.DataSource = bookingData2.DefaultView.ToTable(true, "Topic"); // populate only with the Topic column
Topic.DataTextField = "Topic";
Topic.DataValueField = "Topic";
Topic.DataBind();
Topic.Items.Insert(0, new ListItem("All Topics", "All Topics"));
da.Dispose();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
I have the following code which populates the Specialty dropdownlist and saves it to another cached table:
bookingData = new DataTable();
DataTable DTable_List = new DataTable();
string connString = #"";
string query = #"select * from [DB].dbo.[SP]";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(query, conn);
da.Fill(bookingData);
bookingData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = bookingData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
Specialty.Items.Remove("All Specialties");
Specialty.Items.Insert(0, new ListItem("All Specialties", "All Specialties"));
da.Dispose();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
How can I code the Specialty dropdownlist index change to do the following and save it to a cache table for quick access:
protected void Specialty_SelectedIndexChanged(object sender, EventArgs e)
{
//re-populate the Topic dropdownlist to display all the topics based on the following criteria:
--> Where the Specialty column is either "All Specialties" OR "{specialty selected index value}"
}
Save bookingData2 table in ViewState or Session (I won't recommend to use session though) if it's not too heavy. Otherwise, its better you cache it or query the database again to repopulate it.
Let's assume you save bookingData2 in ViewState as follows in Page_Load
ViewState["bookingData2"] = bookingData2; // This should be before the following line
Topic.DataSource = bookingData2.DefaultView.ToTable(true, "Topic");
Then in your SelectedIndexChanged event do something like this
protected void Specialty_SelectedIndexChanged(object sender, EventArgs e)
{
//re-populate the Topic dropdownlist to display all the topics based on the following criteria:
// Where the Specialty column is either "All Specialties" OR "{specialty selected index value}"
DataTable bookingData2 = (DataTable)ViewState["bookingData2"];
Topic.DataSource = bookingData2.Where(i => i.Specialty == "All Specialties" || i.Specialty == Specialty.SelectedValue).DefaultView.ToTable(true, "Topic"); // populate only with the Topic column
Topic.DataTextField = "Topic";
Topic.DataValueField = "Topic";
Topic.DataBind();
Topic.Items.Insert(0, new ListItem("All Topics", "All Topics"));
}
Update - With Cached object
Do following in Specialty_SelectedIndexChanged event instead of where we used ViewState before.
if (HttpRuntime.Current.Cache["cachedtable2"] != null)
{
DataTable bookingData2 = HttpRuntime.Current.Cache["cachedtable2"] as DataTable;
// Rest of the code
}
I haven't tried this code. Let me know if you find any issues.
This is what solved it for me:
protected void Topic_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (Topic.SelectedIndex == 0)
{
string query = #"Specialty LIKE '%%'";
DataTable cacheTable = HttpContext.Current.Cache["cachedtable"] as DataTable;
DataTable filteredData = cacheTable.Select(query).CopyToDataTable<DataRow>();
filteredData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = filteredData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
}
else
{
string qpopulate = #"[Topic] = '" + Topic.SelectedItem.Value + "' or [Topic] = 'All Topics'"; //#"Select * from [DB].dbo.[table2] where [Specialty] = '" + Specialty.SelectedItem.Value + "' or [Specialty] = 'All Specialties'";
DataTable cTable = HttpContext.Current.Cache["cachedtable2"] as DataTable;
DataTable fData = cTable.Select(qpopulate).CopyToDataTable<DataRow>();
if (fData.Rows.Count > 0)
{
fData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = fData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
}
Specialty.Items.Insert(0, new ListItem("All Specialties", "All Specialties"));
}
}
catch (Exception ce)
{
string error = ce.Message;
}
}
the follwing functions gives me an error:
FillFields("select Housemcode,Name, HP,Rateperhour ,Resource_H_Code FROM House_Machinery where Housemcode like '" + sSearch + "'");
public void FillFields(string sSQL)
{
sCommands.setSqldbCommand(sVariables.sDataSet, sVariables.sSqlDbDataAdapter, sSQL, "House_Machinery");
DataRow sDataRow = sVariables.sDataSet.Tables["House_Machinery"].Rows[0];
txtItemName.Text = sDataRow["Name"].ToString();
txtrate.Text = sDataRow["HP"].ToString();
txtrate.Text = sDataRow["Rateperhour"].ToString();
Variables.StrResourceHeaderCode = sDataRow["Resource_H_Code"].ToString();
}
the error is:
There is no row at position 0.
can any one give an insight on this?
Your query is simply not returning any rows. Try running the SQL query directly in SQL Management Studio to confirm that data is returned.
Incidentally, you can check whether any data is returned at run-time by counting the rows returned:
sCommands.setSqldbCommand(sVariables.sDataSet, sVariables.sSqlDbDataAdapter, sSQL, "House_Machinery");
if(sVariables.sDataSet.Tables["House_Machinery"].Rows.Count == 0)
throw new Exception("No matching rows found");
DataRow sDataRow = sVariables.sDataSet.Tables["House_Machinery"].Rows[0];
1.Just check with Breakpoints if it works well,
2.Does your Sql query working in sql server ? check that it may circle it out.
3.Check your wildcard "%like%",this may have issues.
void somewhereelse()
{
string qry = "select Housemcode,Name, HP,Rateperhour ,Resource_H_Code FROM House_Machinery where Housemcode like '" + sSearch + "'";
filldetails(qry);
}
protected void filldetails(string someqry)
{
Sqlconnection conn = new SqlConnection("Connectionstring");
Datatable dt = new Datatable();
try
{
conn.Open();
SqlDataAdapter dap = new SqlDataAdapter(someqry,conn);
dap.fill(dt);
if(dt.rows.count >0)
{
txtItemName.Text = dt.rows.[0]["Name"].ToString();
txtrate.Text = dt.rows.[0]["HP"].ToString();
txtrate.Text = dt.rows.[0]["Rateperhour"].ToString();
}
}
catch
{
throw;
}
finally
{
if(conn!= null)
{
conn.close();
}
}