i am working on an sale invoice in sale invoice i am auto filling the data about product in its relevant fields, like when user enters product code in product code text box the product name and product price text boxes automatically fills themselves by retrieving data from DB, i want that when user starts type code here the program give the suggestions about all the products in the database. like when user enter 1 the program give suggestion about product codes, product codes starting with 1 show themselves and the user just selects the one he wants to.
the code I've done on text change event of product code text box is
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (txtProductCode1.Text == "")
{
txtProductName1.Text = "";
txtQty.Text = "";
txtSalePrice.Text = "";
txtTotal.Text = "";
}
string sql = "select productprice, ProductName";
sql += " from dbo.productlog";
sql += " where productCode = '" + txtProductCode1.Text + "'"; // Placing ProductCode in single quotes because it's not an int column, but a varchar column, in SQL server
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
if (sdr.Read())
{
txtProductName1.Text = sdr["ProductName"].ToString();
txtSalePrice.Text = sdr["ProductPrice"].ToString();
}
else if (txtProductName.Text == "")
{
goto exitPoint;
}
else if (!sdr.Read())
{
MessageBox.Show("Data not found", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
txtProductName.Focus();
}
exitPoint:
sdr.Close();
rs = null;
cn.Close();
}
how can i show suggestion about product codes in text box?
EDIT:
Its no a windform app means it's a desktop based app and i am creating it in C#.net using VS2010
check this , hope this will work for you
http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.autocompletemode%28v=vs.110%29.aspx
Related
I am new at coding and currently trying to make this barcode tracker program. So far I searched and found what i need but now I couldn't find the answer of this problem (or couldn't understand what people tried to say). So here is my problem:
I am using Ms Access as database but, as numeric datatype Access allows me to enter maximum 10 digit numbers. Also, I know that some barcodes include alphabetic characters so I have to change the datatype to text. If the column's datatype which contains the barcodes is numeric, program works. When i change the column's datatype to text, program gives data type mismatch error.
Here is my code:
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\Barcode\\Database.accdb; Persist Security Info=False");
OleDbDataReader DataReader;
OleDbCommand command;
bool flag = false;
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
}
public void txt_UPC_KeyDown(object sender, KeyEventArgs e)
{
if ((txt_UPC.Text == "") && (e.KeyCode == Keys.Enter))
{
e.Handled = true;
}
else
{
if (e.KeyValue == (char)Keys.Enter)
{
connection.Open();
string SelectQuery = "SELECT * FROM Products where [UPC]=" + txt_UPC.Text.ToString();
command = new OleDbCommand(SelectQuery, connection);
DataReader = command.ExecuteReader(); **//Error occurs here...**
while (DataReader.Read())
{
txtProduct.Text = DataReader["Product"].ToString();
txtPrice.Text = DataReader["Price"] + " ₺";
if (DataReader["UPC"].ToString() == txt_UPC.Text)
{
flag = true;
}
}
if (flag == true)
{
Test.Text = "Known Product";
txt_UPC.Text = "";
flag = false;
}
else
{
Test.Text = "Unknown Product";
}
connection.Close();
}
}
}
}
Suggest use apostrophe delimiters for text type field parameter.
string SelectQuery = "SELECT * FROM Products where [UPC]='" + txt_UPC.Text.ToString() + "'";
You need fully a formed SQL Server expression. You currently have
string SelectQuery = "SELECT * FROM Products where [UPC]=" + txt_UPC.Text.ToString();
Assuming that txt_UPC.Text is a string, you probably need to do this instead:
string SelectQuery = "SELECT * FROM Products where [UPC]= '" + txt_UPC.Text.ToString() + "'";
That encloses your string in the SQL-language mandated single quotes. For what it's worth, you probably don't need the .ToString() on that either.
And, it's a really bad idea to concatenate SQL like you are doing, particularly if you include user inputted text. Read up on "SQL Injection" and use parameterized SQL instead.
I have a button that when pressed, looks for a value based on a listbox choice and if it finds records in the table, it takes that value from listbox and puts it into a session, refreshes the page and the session is then used as a data source, ie. find where session = session.
Now what happens is if i want to do two consecutive searches, the button doesnt store new session, instead it takes the old session. So if I search for x first, then y, it will add x when page is refreshed.
protected void search(object sender, EventArgs e)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Driver WHERE City = '" + JourOrigin.SelectedItem + "' ";//retrieves driver names from table
dr = cmd.ExecuteReader();
dr.Read();
if(Session["city"] != null)
{
Session["city"] = null;
JourOrigin.SelectedValue = null;
}
else
{
if(dr.HasRows)
{
Session["city"] = JourOrigin.SelectedItem.ToString();
Response.Redirect("~/Account/FindDriver.aspx");
NoCity.Visible = false;
}
else
{
DriversJourney.Items.Clear();
DriversJourney.Items.Add("No Drivers in selected city, try another city");
NoCity.Visible = true;
NoCity.Text = "No drivers in selected city, please try another city";
}
}
con.Close();
}
I managed to clear the session if there is a session already, but I have to press value twice to store it. Is it possible to "refresh" a session every time the button is pressed?
You must try this code:
protected void search(object sender, EventArgs e)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Driver WHERE City = '" + JourOrigin.SelectedItem + "' ";//retrieves driver names from table
dr = cmd.ExecuteReader();
dr.Read();
if(Session["city"] != null)
{
Session["city"] = null;
}
if(dr.HasRows)
{
Session["city"] = JourOrigin.SelectedItem.ToString();
Response.Redirect("~/Account/FindDriver.aspx");
NoCity.Visible = false;
}
else
{
DriversJourney.Items.Clear();
DriversJourney.Items.Add("No Drivers in selected city, try another city");
NoCity.Visible = true;
NoCity.Text = "No drivers in selected city, please try another city";
}
con.Close();
}
I am updating a C# UICombo box with an option to show all companies from a DB table but I'm having a hard time getting it working. Currently there are two companies showing. And there should be a third option in which you can select "all".
Basically this is the current code, (bedrijf = company, bedrijven = companies, werknemer = eployee.
private void MainForm_Load(object sender, System.EventArgs e)
{
this.Visible = false;
this.Cursor = Cursors.WaitCursor;
loading = true;
StartupScreen.setStatus("Bezig met laden van overige instellingen...");
StartupScreen.NextValue();
//Alleen de bedrijven tonen waar men recht op heeft
bedrijven.toonUICombo(cbBedrijf, "", "SELECT Bedrijven.id, naam FROM Bedrijven, Werknemer_Bedrijven WHERE Zichtbaar=1 AND Bedrijven.id=Werknemer_Bedrijven.Bedrijven_id AND Werknemer_id=" + Globals.werknemer.getValue("id"));
try
{
cbBedrijf.SelectedValue = Globals.werknemer.getIntValue("DefaultBedrijfId");
cbBedrijf.Visible = (cbBedrijf.Items.Count != 1);
uiTab.SelectedIndex = 1;
}
catch (Exception ex)
{
cbBedrijf.SelectedIndex = 0;
}
As you can see there are two tables. Table one (Companies) contains three companies (Company 1,Company 2 and all) with an id/name pair and some other details.
Table two (Employee_Companies) contains id, Employee id, Companies_id and Visibility.
(Please ignore the table names, they are translated from Dutch)
using (SqlConnection conn = new SqlConnection())
{
try
{
conn.ConnectionString = "data source=yourserver;User ID=userid;Password=password;initial catalog=database;integrated security=False;MultipleActiveResultSets=True;App=EntityFramework";
conn.Open();
SqlCommand cmd = new SqlCommand("your sql query here", conn);
SqlDataReader rd = cmd.ExecuteReader();
cmb_company.Items.Add("3-All");
while (rd.Read())
{
cmb_company.Items.Add(rd.GetValue(0)+"-"+rd.GetValue(1));
//if you need to show both id and company name
}
rd.Close();
conn.close();
}
catch(exception ex)
{
}
}
Hope this can help.. this will show 3 companies in combo box...
1-comp1, 2- comp2, 3-All
And depends on the value selected you should write the query to show the employees..
I am using datagrid view in a windows form application. I have several data grids that display a date date column. When I display my data, the date shows correctly but is always followed by '00:00:00'. How can I change it to only display the date as 'dd/mm'yyyy'.
I build my datagrid as follows:
//Populate customers datagrid view
private void displayInGrid_Customers(string sqlcmd)
{
customersDataGridView.Rows.Clear();
connect.Open();
command.Connection = connect;
command.CommandText = sqlcmd;
reader = command.ExecuteReader();
while (reader.Read())
{
// add a row ( get index )
int arow = customersDataGridView.Rows.Add();
// datagridname.row[index].cells.value = reader[table].tostring()
customersDataGridView.Rows[arow].Cells[0].Value = reader["Customer_ID"].ToString();
customersDataGridView.Rows[arow].Cells[1].Value = reader["Forename"].ToString();
customersDataGridView.Rows[arow].Cells[2].Value = reader["Surname"].ToString();
customersDataGridView.Rows[arow].Cells[3].Value = reader["Address"].ToString();
customersDataGridView.Rows[arow].Cells[4].Value = reader["Town"].ToString();
customersDataGridView.Rows[arow].Cells[5].Value = reader["Postcode"].ToString();
customersDataGridView.Rows[arow].Cells[6].Value = reader["Date_Of_Birth"].ToString();
customersDataGridView.Rows[arow].Cells[7].Value = reader["Phone_Number"].ToString();
customersDataGridView.Rows[arow].Cells[8].Value = reader["Email"].ToString();
customersDataGridView.Rows[arow].Cells[9].Value = reader["Current_Rental"].ToString();
customersDataGridView.Sort(Surname, ListSortDirection.Ascending);
}
reader.Close();
connect.Close();
}
//Display all customers button
private void button_view_all_customers_Click(object sender, EventArgs e)
{
command.CommandText = "SELECT CUSTOMERS.Customer_ID, CUSTOMERS.Forename, CUSTOMERS.Surname, CUSTOMERS.Address, "
+ "CUSTOMERS.Town, CUSTOMERS.Postcode, CUSTOMERS.Date_Of_Birth, CUSTOMERS.Phone_Number, CUSTOMERS.Email, CUSTOMERS.Current_Rental "
+ "from CUSTOMERS LEFT JOIN STOCK ON CUSTOMERS.Current_Rental = STOCK.Product_ID";
string cmd = command.CommandText;
displayInGrid_Customers(cmd);
Also, I have another problem in a different datagrid. This one has a payment column and when I originally created the table in access, the data in the column was like '£4.99' and right justified as expected but when I display it, there is no '£' symbol and it is left justified.
Code for that datagrid is:
//Populate payments datagrid view
private void displayInGrid_Payments(string sqlcmd)
{
paymentsDataGridView.Rows.Clear();
connect.Open();
command.Connection = connect;
command.CommandText = sqlcmd;
reader = command.ExecuteReader();
while (reader.Read())
{
// add a row ( get index )
int arow = paymentsDataGridView.Rows.Add();
paymentsDataGridView.Rows[arow].Cells[0].Value = reader["Customer_ID"].ToString();
paymentsDataGridView.Rows[arow].Cells[1].Value = reader["Payment"].ToString();
paymentsDataGridView.Rows[arow].Cells[2].Value = reader["Payment_Date"].ToString();
}
reader.Close();
connect.Close();
}
//Display all payments
private void button_display_payments_Click(object sender, EventArgs e)
{
command.CommandText = "SELECT PAYMENTS.Customer_ID, PAYMENTS.Payment, PAYMENTS.Payment_Date "
+ "from PAYMENTS LEFT JOIN CUSTOMERS ON PAYMENTS.Customer_ID = CUSTOMERS.Customer_ID";
string cmd = command.CommandText;
displayInGrid_Payments(cmd);
}
For the first part try:
customersDataGridView.Rows[arow].Cells[6].Value = ((DateTime)reader["Date_Of_Birth"]).ToShortDateString()
And for the second part try:
paymentsDataGridView.Rows[arow].Cells[1].Value = reader["Payment"].ToString("C");
paymentsDataGridView.Rows[arow].Cells[1].Value = String.Format("{0:C}", decimal.Parse(reader["Payment"].ToString()));
If it still gives error, try changing decimal for double, although for money and currency I would avoid double because of rounding errors it could give.
I am trying to select film by using on select command, print the title in a label once selected.. that works well.
next part is the selected film will then decrement 1 from the database stock on button click. This is where I think I am getting confused, its showing no errors until the button click takes place.
C# code for update query
protected void Button2_Click(object sender, EventArgs e)
{
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1");
da.InsertCommand = new OleDbCommand("INSERT INTO DVD (Stock) VALUES (#MessageLabel)", conn);
{
da.InsertCommand.Parameters.AddWithValue("#Stock", MessageLabel.Text);
conn.Open();
da.InsertCommand.ExecuteNonQuery();
using (OleDbCommand cmd = new OleDbCommand(myquery, conn))
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
Previous code for select event
public void Latest_DVD()
{
{
using (OleDbDataAdapter dataquer = new OleDbDataAdapter("SELECT Title,Category,Director,Stock,Year FROM DVD ", conn))
{
dataquer.Fill(dt);
}
}
DG_Latest.ShowHeader = true;
DG_Latest.DataSource = dt;
DG_Latest.DataBind();
conn.Close();
conn.Dispose();
}
protected void Latest_DVD_SelectedIndexChanged(Object sender, EventArgs e)
{
GridViewRow row = DG_Latest.SelectedRow;
MessageLabel.Text = "You selected to rent " + row.Cells[1].Text + ".";
}
so I am thinking I have the query wrong and possibly nor retrieve the update from the label but maybe the on select its self... I am not sure through.
the error it is showing is
Data type mismatch in criteria expression.
just after the connection is open
As #afzalulh said, remove the insert part. And change myquery string to be:
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1 WHERE Title = #Title");
var row = DB_Latest.SelectedRow;
var title = row.Cells[0].Text;
var cmd = new OleDbCommand(myquery, conn);
cmd.Parameters.AddWithValue("#Title", title);
With that, you only update Stock for the selected DVD title only. Without adding WHERE clause, the query will decrease stock for all DVDs.
You want to update stock, there's no need to insert. I believe this is what you want:
protected void Button2_Click(object sender, EventArgs e)
{
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1");
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(myquery, conn))
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
EDIT: myquery should include WHERE as suggested by har07. Otherwise it will reduce all DVD's stock by 1.