@Studnet_1999 , based on your description, I almost understand your requirement about your questions.
Here is a code example you could refer to.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static string connstr = "str";
SqlConnection connection=new SqlConnection(connstr);
private void Form1_Load(object sender, EventArgs e)
{
loaddata();
connection.Open();
string sql = "select *from Materials";
SqlCommand sqlCommand = new SqlCommand(sql, connection);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
comboBox1.Items.Add(reader["name_material"].ToString());
}
connection.Close();
comboBox1.SelectedIndexChanged += ComboBox1_SelectedIndexChanged;
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value=comboBox1.SelectedItem.ToString();
connection.Open();
string sql =string.Format("select idmaterial from Materials where name_material='{0}'",value);
SqlCommand sqlCommand = new SqlCommand(sql, connection);
int idmaterial =(int) sqlCommand.ExecuteScalar();
sql = string.Format("select idscrap,Materials_idmaterial from Scraps where Materials_idmaterial={0}", idmaterial);
SqlDataAdapter adapter = new SqlDataAdapter(sql,connection);
DataSet ds = new DataSet();
adapter.Fill(ds);
dataGridView2.DataSource= ds.Tables[0];
connection.Close();
}
private void tabControl1_Click(object sender, EventArgs e)
{
if(tabControl1.SelectedTab.Name== "tabPage1")
{
loaddata();
}
if(tabControl1.SelectedTab.Name == "tabPage2")
{
textBox1.Clear();
comboBox1.Text = "";
}
}
public void loaddata()
{
connection.Open();
string sql = "select *from Materials";
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
adapter.Fill(ds);
dataGridView1.DataSource = null;
dataGridView1.DataSource = ds.Tables[0];
connection.Close();
}
private void button4_Click(object sender, EventArgs e)
{
string value=comboBox1.SelectedItem.ToString();
int quantity=Convert.ToInt32(textBox1.Text);
connection.Open();
string sql = string.Format("select quantity_material from Materials where name_material='{0}'", value);
SqlCommand sqlCommand = new SqlCommand(sql, connection);
double getquantity =Convert.ToDouble(sqlCommand.ExecuteScalar());
double newquantity = getquantity - quantity;
sql = String.Format("update Materials set quantity_material={0} where name_material='{1}'", newquantity, value);
sqlCommand = new SqlCommand(sql,connection);
sqlCommand.ExecuteNonQuery();
Console.WriteLine(getquantity);
connection.Close();
}
}
Note: I don't have mysql database, I used sql database to replace it. You could make some changes based on my code.
Here is my tested result:
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our [documentation][3] to enable e-mail notifications if you want to receive the related email notification for this thread.