ComboBox issue to display values correctly - c#

This program uses fileds there is no data grid. what I am struggling with or you can say I want to correct functions to this is that.
If a user enters ID "1234" and this data already exists in the SQL Database instead of the program crashing or through exception, shows a pop up alert that the data already exists.
The filed Year is a combo box instead of a text box, where we can see years like in a drop down list and if user chooses ID "1234" and chooses 2016 for this only the corresponding amount should appear in the amount text box, or if there are other years for this user ID can be selected and checked the amount.
The program is listing but not showing the year properly, my code is as follows :-
private void btnSearch_Click(object sender, EventArgs e)
{
cmbYear.Items.Clear();
string sql = "";
con.Open();
SqlCommand cmd = new SqlCommand();
try
{
sql += "SELECT m.MemberId, m.Name, m.Address, m.Cellular, m.Email, p.PaymentId, p.Year, p.Amount from Members as m";
sql += " INNER JOIN Payments as p ON m.MemberId = p.MemberId";
sql += " WHERE m.MemberId = '" + tbID.Text + "' ORDER BY p.Year ASC";
cmd.Connection = con;
cmd.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if(dt.Rows.Count >0)
{
for(int i = 0; i<=dt.Rows.Count -1;i++)
{
tbID.Text = dt.Rows[i]["MemberId"].ToString();
tbName.Text = dt.Rows[i]["Name"].ToString();
tbCellular.Text = dt.Rows[i]["Cellular"].ToString();
tbEmail.Text = dt.Rows[i]["Email"].ToString();
tbAddress.Text = dt.Rows[i]["Address"].ToString();
tbAmount.Text = dt.Rows[i]["Amount"].ToString();
cmbYear.Items.Add(dt.Rows[i]["Year"].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
//This part displaying og the existing data from all the fileds

Related

Eliminating an option from a ComboBox (2), based on the input of the first ComboBox (1) c#

I am creating an airline booking system and I have 2 combo boxes. The first is for Departure City and the second is for Arrival City. I want to be able to eliminate the choice in the first combo box from the second, as I don't want the same city to be able to be submitted as both the departure and arrival city. I am querying the city names from a database.
Here is my code:
public partial class main : Form
{
public main()
{
InitializeComponent();
string connectionString = #"Base Schema Name=cyanair;data source=C:\Users\Client 0819\source\repos\Cyanair\cyanair.db";
//Departure ComboBox
SQLiteConnection conn = new SQLiteConnection(connectionString);
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM CyanairAirports";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboDeparture.DataSource = dt;
comboDeparture.ValueMember = "Descriptions";
comboDeparture.DisplayMember = "Descriptions";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Arrival ComboBox
private void comboDeparture_DisplayMemberChanged(object sender, EventArgs e)
{
string connectionString = #"Base Schema Name=cyanair;data source=C:\Users\Client 0819\source\repos\Cyanair\cyanair.db";
SQLiteConnection conn = new SQLiteConnection(connectionString);
**String city = comboDeparture.DisplayMember;**
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM CyanairAirports WHERE Descriptions IS NOT '" + comboDeparture.SelectedValue.ToString() + "'";
richTextBox1.Text = "SELECT * FROM CyanairAirports WHERE Descriptions IS NOT '" + comboDeparture.SelectedValue + "'";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboArrival.DataSource = dt;
comboArrival.ValueMember = "Descriptions";
comboArrival.DisplayMember = "Descriptions";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks :)
It looks like you're handling the DisplayMemberChanged event on comboDeparture, and trying to update the values of comboArrival in that handler. However, DisplayMemberChanged only triggers when the DisplayMember property changes.
DisplayMember only tells the control which property to display on a data bound control. It isn't tied to the index or value selected in the ComboBox. So, the only time the code to populate comboArrival runs is in the constructor when you set comboDepartarture.DisplayMember. Instead, handle either ComboBox.SelectedIndexChanged or ComboBox.SelectedValueChanged and set the items of comboArrival.
A few other important things to note about your code.
First, you should use a parameterized query when running Sql Statements, rather than concatenating strings. Concatenating strings as you're doing opens you up to SQL Injection Attacks. I'm not familiar with SqlLite and can't provide you with an example of how to modify your code, but perhaps this question can help.
Second, you don't need to re-run the query every time you change the selected value in comboDeparture. Just add comboArrival's data source as a field on the Form and you can filter it. For example...
public partial class main : Form
{
// Your constructors...
private void comboDepartures_SelectedIndexChanged(object sender, EventArgs e)
{
if (_arrivalsDataSource == null)
{
_arrivalsDataSource = new System.Data.DataTable();
// Load _arrivalsDataSource from the database, basically how you're doing it now.
comboArrival.DataSource = _arrivalsDataSource.DefaultView;
comboArrival.DisplayMember = "Descriptions"
comboArribal.ValueMember = "Descriptions"
}
if (comboDeparture.SelectedIndex == -1)
{
_arrivalsDataSource.DefaultView.RowFilter = null; // Clear the filter.
}
else
{
// Set the filter.
_arrivalsDataSource.DefaultView.RowFilter = $"Description <> '{comboDeparture.SelectedValue}'";
}
}
private System.Data.DataTable _arrivalsDataSource = null;
}

Fill textbox with an incremented value from access database in C#

I created a C# application to query and insert a product database. However I am here with a small doubt and if anyone can help me i thank you right away.
The following is:
I have a form to insert data into the database created in MS Access 2007, with the values of reference, sale number, client code, client name, quantity and position number in archive;
Here is my code until the moment:
private void btn_save_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=product.accdb");
OleDbCommand check_sn = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([sn] = #sn)", con);
OleDbCommand check_reference = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([reference] = #ref)", con);
OleDbCommand check_number = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([number] = #num)", con);
con.Open();
check_reference.Parameters.AddWithValue("#ref", textBox_ref.Text);
check_sn.Parameters.AddWithValue("#sn", textBox_sn.Text);
check_number.Parameters.AddWithValue("#num", textBox_num.Text);
int refExist = (int)check_reference.ExecuteScalar();
int SNExist = (int)check_sn.ExecuteScalar();
int numExist = (int)check_number.ExecuteScalar();
if (refExist > 0)
{
MessageBox.Show("A product with this reference already exists....!");
}
else if (SNExist> 0)
{
MessageBox.Show("A product with this sale number already exists....!");
}
else if (numExist > 0)
{
MessageBox.Show("A product with this archive number already exists....!");
}
else
{
try
{
String reference = textBox_ref.Text.ToString();
String sn = textBox_ov.Text.ToString();
String cod_client = textBox_cod.Text.ToString();
String client = textBox_cliente.Text.ToString();
String qtd = textBox_qtd.Text.ToString();
String number = textBox_num.Text.ToString(); //This will be the incremented number
String my_query = "INSERT INTO product(reference,sn,cod_client,client,qtd,number)VALUES('" + reference + "','" + sn + "','" + cod_client + "','" + client + "','" + qtd + "','" + number + "')";
OleDbCommand cmd = new OleDbCommand(my_query, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfully...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
con.Close();
}
cleanTextBoxes(this.Controls);
}
}
private void search_btn_Click(object sender, EventArgs e)
{
Form search = new Form_search();
search.Show();
this.Hide();
}
}
}
How can i make it so that instead of manually entering the position number in archive in the textbox it can be automatically filled with the new position in archive. For example, my last product inserted has the position 50 in archive, the new one will automatically be number 51 and so on ... and this number should appear automatically in the textbox so that the user knows what is the number of the new registered product.
Thank you,
Ok i have tried this and works but how i do now to increment this value +1?
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Aneis_Calibre.accdb");
con.Open();
OleDbDataReader myReader = null;
OleDbCommand number = new OleDbCommand("SELECT TOP 1 [number] FROM product Order by [number] desc", con);
myReader = number.ExecuteReader();
while (myReader.Read())
{
textBox_num.Text = (myReader["number"].ToString());
}
con.Close();
Inside your query, you would want to do something along these lines.
INSERT ...
OUTPUT inserted.identity_column
VALUES (...)
That will return a row with a value for the id. The identity column in SQL will always increment automatically for you. Which would alleviate your approach where you grab the last record and do:
int.TryParse(reader["..."]?.ToString(), out int id);
textbox.Text = id++;
By using the scalar, or reader though I would recommend scalar if you return a single column with a modified SQL query would result in the exact newly inserted id.

Maintaining state of checkboxes while filtering record using textbox

I am working on a C# windows application to populate records from SQL Server to data grid view, with dynamic checkbox facility in each row. I want to select selected rows for some purpose via checkbox of that particular row. Till now I successfully achieve my target, but I'm facing a minor issue regarding saving a checked status.
For example I want to check only those records whose Name = Max. I have a textbox in that textbox I call text change event with like Query:
try
{
SqlCommand cmd = null;
SqlConnection con = null; Ranks rank = new Ranks();
con = new SqlConnection(cs.DBcon);
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "Select * from Records where Name like #Name order by Pno";
cmd.Parameters.AddWithValue("#Name", "%" + FilterByNameTextbox.Text.Trim() + "%");
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter1.Fill(dt);
dataGridView1.DataSource = dt;
Make_fields_Colorful();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
If I write Max in filter by name textbox it would return 3 records with name starts with max using like query as I mention code above. So I only check 2 records out of 3 using dynamic checkbox, till now my code runs perfectly. Now I want to check records which name starts from Ali, now when I write ali in my filter by name textbox it will return rows where name like ali , but problem comes here it will remove my previous checked records, so how I would able to save checked records for both max and ali's rows:
Code for adding dynamic checkboxes in each row
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.Name = "checkBoxColumn";
checkBoxColumn.DataPropertyName = "Report";
checkBoxColumn.HeaderText = "Report";
dataGridView1.Columns.Insert(10, checkBoxColumn);
dataGridView1.RowTemplate.Height = 100;
dataGridView1.Columns[10].Width = 50;
Images:
Image 1
Image 2
I suggest you achieve this by caching selected rows, first you should have a list of cached rows:
List<DataGridViewRow> CachedRows = new List<DataGridViewRow>();
then add event handler on cell value change like the following:
dataGridView1.CellValueChanged += view_CellValueChanged;
and the handler should check if the column changed is the checkbox and checked, should be something like the following:
try
{
if(e.ColumnIndex == indexOfCheckBoxColumn)
{
if((bool)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == true)
{
CachedRows.Add((DataGridViewRow)dataGridView1.Rows[e.RowIndex].Clone());
}
else if (CachedRows.Contains(dataGridView1.Rows[e.RowIndex]))//Validate if this works, if not you should associate each row with unique key like for example (id) using a dictionary
{
CachedRows.Remove(dataGridView1.Rows[e.RowIndex]);
}
}
}
catch(Exception ex)
{
}
then after the filter changes, re-add the cached rows again, so code becomes:
try
{
SqlCommand cmd = null;
SqlConnection con = null; Ranks rank = new Ranks();
con = new SqlConnection(cs.DBcon);
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "Select * from Records where Name like #Name order by Pno";
cmd.Parameters.AddWithValue("#Name", "%" + FilterByNameTextbox.Text.Trim() + "%");
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter1.Fill(dt);
dataGridView1.DataSource = dt;
//add folowing
if (CachedRows.Any())
{
dataGridView1.Rows.AddRange(CachedRows.ToArray());
CachedRows.Clear();
}
Make_fields_Colorful();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}

Using checkbox text values to perform search in database

I am working on a project where the user is displayed a image with hotspots. Upon clicking one part he is displayed a dynamically generated checkbox for which the values are picked from database (hotspot are mapped to value displayed).
The problem I am facing is that when the value is a single word (ex. swelling) the code works fine and fetches the possible diseases, but when there are words like (ex. joint pain or nausea with vomiting) i.e the ones which contain space between them (more than one word as a checkbox value) the code does not work.
Here is the code
protected void Button2_Click(object sender, EventArgs e)
{
if (TextBox2.Text != "")
{
connection.Open();
symptons = String.Join(", ", CheckBoxList1.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Text).ToArray());
Label1.Text = symptons;
string query = symptons.Replace(", ", "','");
string cm = "select distinct dname from disease d inner join diseasesymptom ds on ds.did=d.did inner join symptom s on s.sid=ds.sid where s.sname in ('" + query + "')" + "and days >" + TextBox2.Text + " and days<41 order by (days) desc;";
if (symptons != "")
{
MySqlCommand cmd = new MySqlCommand(cm, connection);
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = connection;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
else
{
Label1.Text = "select at least one symptom";
}
}
else
{
string script = "alert(\"We can't predict without all inputs :(\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
}
I think it has something to do with Join and Replace that I am performing.
never mind guys..I got it. I was missing a column value in database that helped in searching (hint : its 'days') . Anyway thanks for anyone who read this. :)

update data from MySQL

hello i create a program that can add/edit/delete data from database
i've done the Add data process but my problem is i cannot do the Edit and Delete data.
whenever i click the button Edit the Error message appear
here is the error message:
"Dynamic SQL generation for the UpdateCommand is not supported againts a SelectedCommand that does not return any key column information"
and this is my code for button edit
try
{
string contactNumVal = txtCcontact.Text;
if (contactNumVal.Length < 11)
{
MessageBox.Show("The Contact Number must have 11 digit");
}
else
{
DialogResult dw;
dw = MessageBox.Show("Are you sure you want to Edit this data", "Confirm Deletion", MessageBoxButtons.YesNo);
if (dw == DialogResult.Yes)
{
string MyConString = "SERVER=localhost;" +
"DATABASE=prototype_db;" +
"UID=root;";
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand command = connection.CreateCommand();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter("Select ClientName,ClientAddress,ClientContactNo,ClientContactPerson from client_profile where ClientName like '%"+txtCname.Text+"%'" +" ",connection);
da.Fill(dt);
dt.Rows[0].BeginEdit();
dt.Rows[0][0] = txtCname.Text;
dt.Rows[0][1] = txtCaddress.Text;
dt.Rows[0][2] = txtCcontact.Text;
dt.Rows[0][3] = txtCconPer.Text;
dt.Rows[0].EndEdit();
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
da.Update(dt);
connection.Close();
MessageBox.Show("Data is now updated");
}
}
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
thanks for the Answers
The DataAdapter needs to get information on the Primary Key of your table if you want it to be able to execute UPDATE and DELETE (no problems with SELECT and INSERT) but your query doesn't return this information because the Client_ID field is not enclosed in your command text
So you should change your code to
using(MySqlConnection connection = new MySqlConnection(MyConString))
{
connection.Open();
DataTable dt = new DataTable();
using(MySqlDataAdapter da = new MySqlDataAdapter("Select Client_ID, ClientName, " +
"ClientAddress, ClientContactNo,ClientContactPerson " +
"from client_profile where ClientName like #cname",connection))
{
da.SelectCommand.Parameters.AddWithValue("#cname", "%" + txtCname.Text +"%");
da.Fill(dt);
}
}
Notice also that I have removed the string concatenation of the ClientName value used in the WHERE condition. Use always parameters and not text directly typed by your user when you build sql commands. In this way you avoid SQL Injection problems and parsing problems (single quotes inside txtCName textbox would break the string concatenation)
After adding the Client_ID as above you should also change the index used to update the row values
dt.Rows[0][1] = txtCname.Text;
dt.Rows[0][2] = txtCaddress.Text;
dt.Rows[0][3] = txtCcontact.Text;
dt.Rows[0][4] = txtCconPer.Text;

Categories

Resources