Showing "all" companies from sql database in c# - c#

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

Related

make many mysql command in one connection in c# visual studio & unknown column in where clause

I have mySql database contains ID, projectName, companyName, projectNum, .. etc
I need to create Combobox that display projectName (project name isn't unique)
when I try to execute this the following error appears:
"Unknown column 'proj2' in where clause"
even though when I try to print this value it prints successfully in my code.
so I changed to display ID in Combobox and works well
now I need if I choose one ID to fill some fields (projectName, companyName, projectNum) then display values in other Combobox (e.g Combobox2) it has item number which is not unique and it
depend on projectName field.
I try to make one connection and two connection but both of them didn't work.
nothing appears in Combobox2
when I try to choose ID from first Combobox the same error appears:
"Unknown column 'proj2' in where clause"
I don't know if should I change the design of the database.
again I should mention that project name, company name, project number may be repeated in more than 50 records.
below is the code
first function to fill the first Combobox:
private void Form2_Load(object sender, EventArgs e)
{
try
{
// String getQuery = "Select projectName From ubc.BOQ_Table Group By projectName";
String getQuery = "Select ID From ubc.BOQ_Table";
connection.Open();
MySqlCommand command = new MySqlCommand(getQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
comboBox1.Items.Add(reader.GetString("ID"));
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
second function to fill fields depend on choosing ID:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//get vaalue of selected project
selectedProject = comboBox1.SelectedItem.ToString();
String selectQuery = "Select * From ubc.BOQ_Table where ID=" + selectedProject;
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
projectNameText.Text = reader.GetString("projectName");
projectName = projectNameText.Text;
companyNameText.Text = reader.GetString("companyName");
projectNumber.Text = reader.GetInt32("projectNumber").ToString();
reader.Close();
}
command.CommandText = "Select itemNum From ubc.BOQ_Table where projectName=" + projectName;
command.ExecuteNonQuery();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
comboBox2.Items.Add(reader.GetString("itemNum"));
}
}
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
This line of code is causing the problem:
command.CommandText = "Select itemNum From ubc.BOQ_Table where projectName=" + projectName;
As commenters have mentioned, concatenating strings is causing both the syntax error and makes your code vulnerable to SQL injection attacks. The solution is to use "parameterized queries" by putting the variable in a MySqlParameter object.
command.CommandText = "Select itemNum From ubc.BOQ_Table where projectName=#projectName;";
command.Parameters.AddWithValue("#projectName", projectName);
using (var reader = command.ExecuteReader())
{
// ...
(You may find some people saying "don't use AddWithValue", but that's an objection that applies just to SqlCommand; there's no good reason to avoid using it with MySqlCommand.)

C#, Access Search through multiple tables for a Serial Number

I have 1 Access database with 2 tables. I am using a C# winforms application. I have Serial Number fields in each table but nothing is related. I have a form with a text field and a button to search for a Serial Number, then will return results into a datagrid on the form. Currently I can simply search 1 table. What I would like to do is type in the number, hit the button and return the value after searching both tables. I would rather do this without a union because somehow I need to set the table name in a text box when the results return.
private void btnSearch_Click(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand();
OleDbDataAdapter db = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
if (!string.IsNullOrEmpty(txtSerial.Text))
{
try
{
connection.Open();
command.Connection = connection;
command.Transaction = transaction;
command.Parameters.Add("#searchSerial", OleDbType.VarWChar).Value = txtSerial.Text;
string searchFB = "SELECT (SerialNumber) FROM Inventory WHERE SerialNumber = #searchSerial";
command.CommandText = searchFB;
db.Fill(dt);
dgResults.DataSource = dt;
connection.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
}

Refreshing the combobox after inserting data in mysql c#

Hello so i want to refresh my combobox after i add or delete data from it now if i add data it doesnt get refreshed i have to rerun the program to see the changes but i want to get it refresh in the time i add the data..
the code when i add data:
private void button5_Click(object sender, EventArgs e)
{
MySqlConnection dataConnection = new MySqlConnection();
dataConnection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
dataConnection.Open();
MySqlTransaction transakcija = dataConnection.BeginTransaction();
MySqlCommand dataCommand = new MySqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.Transaction = transakcija;
try
{
dataCommand.CommandText = "Insert INTO filmi.film (film) VALUES ('" + this.tB_Dodaj.Text + "')";
dataCommand.CommandType = CommandType.Text;
dataCommand.ExecuteNonQuery();
transakcija.Commit();
MessageBox.Show("You added a new movie!");
}
catch (Exception eks)
{
transakcija.Rollback();
MessageBox.Show("Movie couldnt be added!!\n" + eks.Message);
}
finally
{
dataCommand.Connection.Close();
}
}
and with each insert the data gets displayed in the combobox but only when i rerun the program
this is how i fill combobox:
void Fillcombo()
{
string constring = "datasource=localhost;port=3306;username=root;password=";
string Query = "SELECT * FROM filmi.film ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("film");
comboBox1.Items.Add(sName);
comboBox2.Items.Add(sName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i have to rerun the program to see the changes but i want to get it
refresh in the time i add the data..
I suspect that you are calling the Fillcombo() method in Form_Load event handler.
if you want to update the combobox for every insert and delete operations in your table you need to call Fillcombo() immediatly after executing the command.
Try This:
int status = dataCommand.ExecuteNonQuery();
transakcija.Commit();
if(status > 0)
{
Fillcombo();
MessageBox.Show("You added a new movie!");
}
in your FillCombo clear the items before adding the new items to remove the duplicates.
comboBox1.Items.Clear(); //add this statetement before adding items
comboBox2.Items.Clear(); //add this statetement before adding items
while (myReader.Read())
{
string sName = myReader.GetString("film");
comboBox1.Items.Add(sName);
comboBox2.Items.Add(sName);
}
ADO.NET object works in a disconnected state, so, adding a record to your datatable doesn't automatically shows up in your combo. You need to call again FillCombo, (clearing the items already in combos, going again to the database to retrieve every record again, adding them to your comboboxes) or just simply adding the film to your already filled combos as a single item
Also pay attention to Sql Injection (use always a parameterized query)
private void button5_Click(object sender, EventArgs e)
{
string conString = "datasource=localhost;port=3306;username=root;password=";
string cmdText = "Insert INTO filmi.film (film) VALUES (#film)";
using(MySqlConnection dataConnection = new MySqlConnection(conString))
using(MySqlCommand dataCommand = new MySqlCommand(cmdText, dataConnection))
{
try
{
dataConnection.Open();
dataCommand.Parameters.AddWithValue("#film", this.tB_Dodaj.Text);
// If ExecuteNonQuery returns a value > 0 then your record has been inserted
// Just add the name of the film to the two combos
if(dataCommand.ExecuteNonQuery() > 0)
{
MessageBox.Show("You added a new movie!");
comboBox1.Items.Add(this.tB_Dodaj.Text);
comboBox2.Items.Add(this.tB_Dodaj.Text);
}
}
catch(Exception ex)
{
MessageBox.Show("Fail to add a new movie! " + ex.Message);
}
}
}
As a last note, watch carefully your fillcombo method. You don't close and dispose the connection.

show suggestions on text box

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

No Value Give For One Or More Parameters?

i have a buttonfield in a gridview, when i press that button it takes the id value from the first column, i use that id in a select statement, to get data from the table, but i get this error "No Value Give For One Or More Parameters"
protected void grdData_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdData.SelectedRow;
string id = row.Cells[1].Text;
try
{
conn.ConnectionString = conn_string;
conn.Open();
mySQLCommand.Connection = conn;
mySQLCommand.CommandText = "Select [Movie_Description],[Movie_Image] from Movie_tbl where Movie_ID = #Movie_ID";
mySQLCommand.Parameters.Add("#Movie_ID", OleDbType.VarChar).Value = id;
myDataReader = mySQLCommand.ExecuteReader();
if (myDataReader.Read())
{
txtDescription.Text = myDataReader["Movie_Description"].ToString();
}
else
{
txtDescription.Text = "No Such Movie";
}
}
catch (Exception ex)
{
throw ex ;
}
}
I haven't worked with mySQL much, but I'm pretty sure you don't want an OleDbType.VarChar parameter. I haven't seen that used outside of MS Access. Try:
mySQLCommand.Parameters.AddWithValue("#Movie_ID", id);
if that fails, maybe try
mySQLCommand.Parameters.Add(new MySqlParameter("#Movie_ID", id));
mySQLCommand is of type MySqlCommand in your code, right?

Categories