I have a registration application for a Windows Surface Tablet PC.
It works brilliantly but there's one more thing i need to work:
The registration works by either being in an Online State(For a Staff Register), or an Offline State(For Student Event Registrations).
When it's in its Online State, we scan barcodes in to it which holds 6 digits + 'L' , which goes to the database and pulls out the Staff Members name and 6 digit code, then it will list the Staff Members name in order down the listbox.
What i am looking to do is List the time it was first entered into the application, and then when they scan the same code again, instead of removing the first entry it will add another time onto the existing line, such as:
First Scan:
Ryan Gillooly (123456) Time: 11:40
Second Scan:
Ryan Gillooly (123456) Time: 11:40 Time: 13:26
and so on and so forth.
Here is the code :
Object returnValue;
string txtend = textBox1.Text;
if (e.KeyChar == 'L')
{
DBConnection.Open();
}
if (DBConnection.State == ConnectionState.Open)
{
if (textBox1.Text.Length != 6) return;
{
cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =#Name");
cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(#"L", "")));
cmd.CommandType = CommandType.Text;
cmd.Connection = DBConnection;
returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(#"L", "") + ")";
DBConnection.Close();
if (listBox1.Items.Contains(returnValue))
{
for (int n = listBox1.Items.Count - 1; n >= 0; --n)
{
string removelistitem = returnValue.ToString();
if (listBox1.Items[n].ToString().Contains(removelistitem))
{
//listBox1.Items.Add(" " + "\t Time:" + " " + DateTime.Now.ToString("HH.mm"));
listBox1.Items.RemoveAt(n);
}
}
}
else
listBox1.Items.Add(returnValue + "\t Time:" + " " + DateTime.Now.ToString("HH.mm"));
textBox1.Clear();
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName);
foreach (object item in listBox1.Items)
SaveFile.WriteLine(item.ToString());
SaveFile.Flush();
SaveFile.Close();
if (listBox1.Items.Count != 0) { DisableCloseButton(); }
else
{
EnableCloseButton();
}
Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
e.Handled = true;
}
}
Try something like this:
.....
DBConnection.Close();
bool found=false;
foreach (var item in listBox1.Items)
{
var entry = item.ToString();
if (entry.Contains(returnvalue.ToString()))
{
listBox1.Items.Remove(item);
listBox1.Items.Add(entry + " extra add");
found = true;
break;
}
}
if (!found)
{
listBox1.Items.Add(returnvalue.ToString());
}
textBox1.Clear();
.....
UPDATE
Regarding your extra question in the comments:
You could use string.LastIndexOf to see which word was added last: "In" or "Out".
And then you take the other.
LastIndexOf returns the index of the last occurence of the searchstring, or -1 when it's not present.
Out of my mind you would get something like:
private string CreateNewEntry(string current)
{
var indexIn = current.LastIndexOf("in"); // Get the last index of the word "in"
var indexOut = current.LastIndexOf("out"); // Get the last index of the word out
if (indexOut > indexIn)
{
return current + " in "; // if the last "out" comes after the last "in"
}
else
{
// If the last "in" comes after the last "out"
return current + " out ";
}
}
This will return the current entry + " in " or " out ".
Anbd then you just have to add your extra stuff to it.
To call this, replace the Add-sentences with:
listBox1.Items.Add(CreateNewEntry(entry) + " extra stuff");
Related
The below method has a command that prints out the rows of my database in the textbox. It only prints out maxDataBaseListings # of rows. However, it prints them out from oldest date to newest date. If maxDatabaseListings is 10, and my 11th entry has an newer date than my 10th entry, it won't display.
How can I reverse the ORDER BY command to show the newest dates first? This way, when the method is called, it will refresh the table with the newest date listed first.
public void refreshListing(TextBox inputTextBox, TextBox inputMaxDatabaseListings)
{
if (currentlyConnectedToADatabase)
{
maxDatabaseListings = returnMaxListings(inputMaxDatabaseListings.Text, numberOfDatabaseListings);
inputTextBox.Text = "";
cnn.Open();
//COMMAND HERE
command = new SqlCommand("SELECT * FROM tcn.Demo ORDER BY DateTimeOfInsertion, SomeNumber, SomeText, AnotherNumber", cnn);
reader = command.ExecuteReader();
theTextBox = inputTextBox;
int i =0;
if (reader.HasRows)
{
while (reader.Read() && i < maxDatabaseListings)
{
string printString = int.Parse(reader["SomeNumber"].ToString()) + " " + reader["SomeText"].ToString() + " " + int.Parse(reader["AnotherNumber"].ToString()) + " at " + reader["DateTimeOfInsertion"].ToString() + Environment.NewLine;
theTextBox.AppendText(printString);
i++;
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
cnn.Close();
}
else
{
MessageBox.Show("You must first connect to a database!");
}
}
ORDER BY column_1 DESC, column_2, column_n
I am trying to make this code work fine as i can but i couldnt,i am using cookie and i want to rebind my ListView depending on cookie Location but i am getting error message: "Must declare the scalar variable "#Location"."
protected void Sortcarbtn_Click(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies.Get("Location");
using (SqlConnection carcon = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
if (cookie != null)
{
string CarSqlST = #"SELECT DISTINCT AdsID, Section, Category, Country, Maker, Gear, Condition, Status, State, City, AdsTit,
SUBSTRING(AdsDesc,1,155) as AdsDesc, Year, AdsPrice, Img1 From ads Where 1=1 AND Category=#CATE AND Country = #Location ";
var Location = Convert.ToString(cookie["Location"]);
var cat = Convert.ToString(Request.QueryString["cat"]);
string condition = "";
if (barndcardrlst.SelectedValue != "")
{
condition += " and Maker='" + barndcardrlst.SelectedValue + "'";
}
if (GearDrDw.SelectedValue != "")
{
condition += " and Gear='" + GearDrDw.SelectedValue + "'";
}
if (carstatedrdolst.SelectedValue != "")
{
condition += " and State='" + carstatedrdolst.SelectedValue + "'";
}
if (citiesdrdolst.SelectedValue != "")
{
condition += " and City='" + citiesdrdolst.SelectedValue + "'";
}
if (CarCondDrDw.SelectedValue != "")
{
condition += " and Condition='" + CarCondDrDw.SelectedValue + "'";
}
if (CarstusDRDL.SelectedValue != "")
{
condition += " and Status='" + CarstusDRDL.SelectedValue + "'";
}
if ((CarPriceFrmDrDw.SelectedValue != "") && (CarPriceToDrDw.SelectedValue != ""))
{
condition += " and AdsPrice BETWEEN " + CarPriceFrmDrDw.SelectedValue + " AND " + CarPriceToDrDw.SelectedValue;
}
if ((CarYearfrmDrDw.SelectedValue != "") && (CarYeartoDrDw.SelectedValue != ""))
{
condition += " and Year BETWEEN " + CarYearfrmDrDw.SelectedValue + " AND " + CarYeartoDrDw.SelectedValue;
}
DataTable cdt = new DataTable();
carcon.Open();
SqlCommand ccmd = new SqlCommand();
ccmd.Connection = carcon;
ccmd.CommandType = CommandType.Text;
ccmd.Parameters.AddWithValue("#Country", Location);
ccmd.Parameters.AddWithValue("#CATE", cat);
ccmd.CommandText = CarSqlST + condition;
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = ccmd;
ad.Fill(cdt);
cateshowlistview.DataSource = cdt;
cateshowlistview.DataBind();
}
}
Change "#Country" in
ccmd.Parameters.AddWithValue("#Country", Location);
to be "#Location"
ccmd.Parameters.AddWithValue("#Location", Location);
you defined the Country in the SQL Statement to be #Location
string CarSqlST = #"SELECT ... AND Category=#CATE AND Country = #Location ";
Update
To prevent SQL Injection hacks and to allow for SQL to reuse the query options all the fileters where you are concat the string together you should just use SQL Parameters. To make it easy I create a parameters dictionary to add to. Then at the end loop through the dictionary to fill in the SQL Parameters. I also switched it to string builder since could be doing a lot of string concats. I didn't test this code because I don't have your objects or tables or connections.
using (var carcon = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString)))
{
if (cookie != null)
{
// Parameters for SQL
var parameters = new Dictionary<string, object>();
// string builder to build up SQL Statement
var CarSqlST = new StringBuilder(
"SELECT DISTINCT AdsID, Section, Category, Country, Maker, Gear, Condition, Status, State, City, AdsTit, " +
"SUBSTRING(AdsDesc,1,155) as AdsDesc, Year, AdsPrice, Img1 From ads " +
"Where Category = #pCATE AND Country = #pLocation ");
parameters.Add("#pCATE", Request.QueryString["cat"].ToString());
parameters.Add("#pLocation", cookie["Location"]);
if (barndcardrlst.SelectedValue != "")
{
CarSqlST.Append(" and Maker= #pMaker");
parameters.Add("#pMaker", barndcardrlst.SelectedValue);
}
if (GearDrDw.SelectedValue != "")
{
CarSqlST.Append(" and Gear= #pGear");
parameters.Add("#pGear", GearDrDw.SelectedValue);
}
if (carstatedrdolst.SelectedValue != "")
{
CarSqlST.Append(" and State= #pState");
parameters.Add("#pState", carstatedrdolst.SelectedValue);
}
if (citiesdrdolst.SelectedValue != "")
{
CarSqlST.Append(" and State= #pCity");
parameters.Add("#pCity", citiesdrdolst.SelectedValue);
}
if (CarCondDrDw.SelectedValue != "")
{
CarSqlST.Append(" and Condition= #pCondition");
parameters.Add("#pCondition", CarCondDrDw.SelectedValue);
}
if (CarstusDRDL.SelectedValue != "")
{
CarSqlST.Append(" and Status= #pStatus");
parameters.Add("#pStatus", CarstusDRDL.SelectedValue);
}
if ((CarPriceFrmDrDw.SelectedValue != "") && (CarPriceToDrDw.SelectedValue != ""))
{
CarSqlST.Append(" and AdsPrice BETWEEN #pLowPrice AND #pHighPrice");
parameters.Add("#pLowPrice", CarPriceFrmDrDw.SelectedValue);
parameters.Add("#pHighPrice", CarPriceToDrDw.SelectedValue);
}
if ((CarYearfrmDrDw.SelectedValue != "") && (CarYeartoDrDw.SelectedValue != ""))
{
CarSqlST.Append(" and Year BETWEEN #pLowYear AND #pHighYear");
parameters.Add("#pLowYear", CarYearfrmDrDw.SelectedValue);
parameters.Add("#pHighYear", CarYeartoDrDw.SelectedValue);
}
DataTable cdt = new DataTable();
SqlCommand ccmd = carcon.CreateCommand();;
ccmd.CommandType = CommandType.Text;
// Add all the parameters into this command
foreach (var parameter in parameters)
{
ccmd.Parameters.Add(parameter.Key, parameter.Value);
}
// set the command text from string builder
ccmd.CommandText = CarSqlST.ToString();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = ccmd;
}
}
You could have created the command at the top and filled in the sql parameters right away instead of the dictionary but I like the dictionary approach better in case something happens - exception or we need to bail we never created the SQL Command.
I want to fetch some data from two different tables PRO and OPN_STK , in some controls like textboxs and datagridview . when i am selecting data from one table i.e. PRO ,the code is working perfect but when i applied same code just next to it , in same event for fetching data from another table i.e. OPN_STK it throws exception "object refrence not set to an instance of object" . I tried to know about the problem but now I'm blank , this is what I did ,
private void comboProname_TextChanged(object sender, EventArgs e)
{
dataGridView3.Rows.Clear();
dataGridView2.Rows.Clear();
//if (get == false) //in case when i need to apply condition which I dont prefer
{
string _sql = "select DISTINCT P_batchno,P_sh from PRO where P_name='" + comboProname.Text + "'";
if (comboBthNo.Text != "")
_sql += " AND P_batchno='" + comboBthNo.Text + "' ";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboBthNo.Text == "")
{
dataGridView3.Visible = true;
int i = 0;
dataGridView3.Rows.Insert(i);
dataGridView3.Rows[i].Cells[0].Value = dr["P_batchno"].ToString();
dataGridView3.Focus();
}
sh = dr["P_sh"].ToString();
}
}
//else if (get == true) // opnstk
{
string _sql = "select DISTINCT P_batchno,P_sh from OPN_STK where P_name='" + comboProname.Text + "'";
if (comboBthNo.Text != "")
_sql += " AND P_batchno='" + comboBthNo.Text + "' ";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboBthNo.Text == "")
{
dataGridView3.Visible = true;
int i = 0;
dataGridView3.Rows.Insert(i);
dataGridView3.Rows[i].Cells[0].Value = dr["P_batchno"].ToString();
dataGridView3.Focus();
}
sh = dr["P_sh"].ToString();
}
}
getdata();
}
private void comboBthNo_TextChanged(object sender, EventArgs e)
{
dataGridView3.Rows.Clear();
dataGridView2.Rows.Clear();
// if (get == false)
{
string _sql = "SELECT DISTINCT P_name,P_pack,P_comp,P_expdate,P_rate,P_mrp from PRO where P_batchno='" + comboBthNo.Text + "'";
if (comboProname.Text != "")
_sql += " AND P_name='" + comboProname.Text + "'";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboProname.Text == "")
{
dataGridView2.Visible = true;
int i = 0;
dataGridView2.Rows.Insert(i);
dataGridView2.Rows[i].Cells[0].Value = dr["P_name"].ToString();
dataGridView2.Focus();
}
tbMrp.Text = (dr["P_mrp"].ToString());
dateTimePicker2.Text = (dr["P_expdate"].ToString());
}
}
// else if (get == true) ///// opn stk ///////
{
string _sql = "SELECT DISTINCT P_name,P_pack,P_comp,P_expdate,P_rate,P_mrp from OPN_STK where P_batchno='" + comboBthNo.Text + "'";
if (comboProname.Text != "")
_sql += " AND P_name='" + comboProname.Text + "'";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows) // I get exception here only on dt
{
if (comboProname.Text == "")
{
dataGridView2.Visible = true;
int i = 0;
dataGridView2.Rows.Insert(i);
dataGridView2.Rows[i].Cells[0].Value = dr["P_name"].ToString();
dataGridView2.Focus();
}
tbMrp.Text = (dr["P_mrp"].ToString());
dateTimePicker2.Text = (dr["P_expdate"].ToString());
}
}
getdata();
}
i would appriciate any help ,thanks in advance .
Put a breakpoint in your code, debug and check that OPN_STK is not null. If it is null that would be your problem.
I am building a simple Point of Sale program and working on a "search invoice" button that allows up to 3 search criteria (InvoiceID , ClientName, and ClientID). These are the names of 3 of the columns in the table named "Invoicing".
InvoiceID is the key column of type Int32, ClientName is of type String, ClientID is of type Int32. ClientName and ClientID searches work perfect.
MY PROBLEM: If I include InvoiceID in the select query, I get the following error. And I have spent a few days trying to figure it out.
ERROR: Database Error: Datatype mismatch in criteria expression.
Can you more experienced programmers help me out? thank you!
String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data" + #" Source=TESTDB.accdb";
String tableName = "Invoicing";
String query = String.Format("select * from [{0}] where", tableName);
//ADD IN SEARCH CRITERIA
int filled = 0;
if (invoiceBox.Text != "") { query += " InvoiceID='" + invoiceBox.Text+"'"; filled += 1; }
/*if (DateCheckBox.Checked == true)
{
if (filled>=1) { query += " and DateNTime='" + monthCalendar1.SelectionStart.ToString() + "'"; filled += 1; }
else { query += " DateNTime='" + monthCalendar1.SelectionStart.ToString()+ "'"; filled += 1; }
}
* */
if (ClientNameBox.Text != "") //Doesnot work
{
if (filled >= 1) { query += " and Client='" + ClientNameBox.Text + "'"; filled += 1; }
else { query += " Client='" + ClientNameBox.Text + "'"; filled += 1; }
}
if (ClientIDBox.Text != "") //THIS search criteria works!!!!
{
if (filled >= 1) { query += " and ClientID='" + ClientIDBox.Text + "'"; filled += 1; }
else { query += " ClientID='" + ClientIDBox.Text + "'"; filled += 1; }
}
//CHECK IF SEARCH CRITERIA ARE PRESENT
if (filled < 1) { MessageBox.Show("At least One Search criteria above is required"); return; }
DataSet dsInvoicing = new DataSet();
OleDbConnection conn = new OleDbConnection(connectionString);
try
{
//Open Database Connection
conn.Open();
OleDbDataAdapter daInvoicing = new OleDbDataAdapter(query, conn);
//Fill the DataSet
daInvoicing.Fill(dsInvoicing, tableName);
//MessageBox.Show("dsInventory has "+dsInventory.Tables[0].Rows.Count+" search results");
conn.Close();
this.dataGridView1.DataSource = dsInvoicing.Tables[0];
}
catch (OleDbException exp){ MessageBox.Show("Database Error: " + exp.Message.ToString());}
Need more information? I will post up more if I haven't provided enough.
DATABASE INFORMATION or other.
Thank you very much to all programmers.
Looks like the data type of InvoiceID in your database is some numeric kind. While in query you are treating it as string. Try not to wrap InvoiceID value in single quotes.
I am accesing value from database and displaying them on form ,i have successfully displayed retrived value in textbox and radiobox but i am not able to display them in combbox .
In combox items I have values(1 2 3 4) in this combox i want to display fetched value from database for eg. i accesed value 4 for combbox then it should display 4 value selected in it .
how could i achieve this?
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
string columns = db.GetEditQuestions(qid_value);
string[] coldata=columns.Split('~');
txtQuestion.Text = coldata[1];
txtOption1.Text = coldata[2];
txtOption2.Text = coldata[3];
txtOption3.Text = coldata[4];
txtOption4.Text = coldata[5];
string a = coldata[6];
if (a == "1")
{
radioButton1.Checked = true;
}
else if (a == "2")
{
radioButton2.Checked = true;
}
else if (a == "3")
{
radioButton3.Checked = true;
}
else if (a == "4")
{
radioButton4.Checked = true;
}
cmbMarks.ValueMember = coldata[7];//in cmbMarks.ValueMember i am getting fetched value but it is not displaying in combbox ,where i am wrong?
}
GetEditQuestions(qid_value) Code
public string GetEditQuestions(int qid)
{
string data = "";
try
{
string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
if (rs.Read())
{
data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
}
}
catch (Exception err)
{
}
return data;
}
Thanks in Advance for any help
cmbMarks.Text = coldata[7].Substring(1)
See this MSDN page. The .Substring(1) is assuming that coldata[7] is a string with a $ as the first character.