How can i shorten this code in c#?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btn1_Click(object sender, EventArgs e)
    {
        try
        {
            //This is my connection string  assigned the database file address path  
            string MyConnection2 = "datasource=127.0.0.1;port=3306;username=root;password=;";
            //This is my insert query in which taking input from the user through windows forms  
            string Query = "insert into schule.schule(id,name,schuler,adresse,baujahr) values('" + this.IdTextBox.Text + "','" + this.NameTextBox.Text + "','" + this.SchulerTextBox.Text + "','" + this.AdresseTextbox.Text + "','" + this.BaujahrTextbox.Text + "');";
            //This is  MySqlConnection here i have created the object and pass my connection string.  
            MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            //This is command class which will handle the query and connection object.  
            MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
            MySqlDataReader MyReader2;
            MyConn2.Open();
            MyReader2 = MyCommand2.ExecuteReader();     // Here our query will be executed and data saved into the database.  
            MessageBox.Show("Save Data");
            while (MyReader2.Read())
            {
            }
            MyConn2.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btn2_Click(object sender, EventArgs e)
    {
        try
        {
            //This is my connection string i have assigned the database file address path  
            string MyConnection2 = "datasource=127.0.0.1;port=3306;username=root;password=;";
            //This is my update query in which i am taking input from the user through windows forms and update the record.  
            string Query = "update schule.schule set id='" + this.IdTextBox.Text + "',name='" + this.NameTextBox.Text + "',schuler='" + this.SchulerTextBox.Text + "',adresse='" + this.AdresseTextbox.Text + "',baujahr='" + this.BaujahrTextbox.Text + "' where id='" + this.IdTextBox.Text + "';";
            //This is  MySqlConnection here i have created the object and pass my connection string.  
            MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
            MySqlDataReader MyReader2;
            MyConn2.Open();
            MyReader2 = MyCommand2.ExecuteReader();
            MessageBox.Show("Data Updated");
            while (MyReader2.Read())
            {
            }
            MyConn2.Close();//Connection closed here  
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btn3_Click(object sender, EventArgs e)
    {
        try
        {
            string MyConnection2 = "datasource=127.0.0.1;port=3306;username=root;password=;";
            string Query = "delete from student.studentinfo where id='" + this.IdTextBox.Text + "';";
            MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
            MySqlDataReader MyReader2;
            MyConn2.Open();
            MyReader2 = MyCommand2.ExecuteReader();
            MessageBox.Show("Data Deleted");
            while (MyReader2.Read())
            {
            }
            MyConn2.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btn4_Click(object sender, EventArgs e)
    {
        try
        {
            string MyConnection2 = "datasource=127.0.0.1;port=3306;username=root;password=;";
            //Display query  
            string Query = "select * from schule.schule;";
            MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
            //  MyConn2.Open();  
            //For offline connection we weill use  MySqlDataAdapter class.  
            MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
            MyAdapter.SelectCommand = MyCommand2;
            DataTable dTable = new DataTable();
            MyAdapter.Fill(dTable);
            dg1.DataSource = dTable; // here assign dTable object to the dataGridView1 object to display data.               
                                               // MyConn2.Close();  
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}
}
using System.Data.Common;

namespace YOURNAMESPACE
{
    public interface IDbConnectionFactory
    {
        DbConnection CreateConnection();
    }
}
using System;
using System.Data.Common;
using System.Data.SqlClient;

namespace YOURNAMESPACE
{
    public class MySqlConnectionFactory: IDbConnectionFactory
    {
        private string _connectionString;

        public MySqlConnectionFactory(string connectionString)
        {
                _connectionString = connectionString;
        }

        public DbConnection CreateConnection()
        {
            return new MySqlConnection(_connectionString);
        }
    }
}
***USING STATEMENTS***
***YOUR NAMESPACE BLOCK***

public partial class Form1 : Form
{
    public Form1(IConnectionFactory connectionFactory)
    {
        InitializeComponent();
        _connectionfactory = connectionFactory;
    }

    private IConnectionFactory _connectionfactory;

    private DbDataReader ExecuteQuery(string query)
    {
        using DbConnection connection = _dbConnectionFactory.CreateConnection();
        using DbCommand command = connection.CreateCommand();
        command.CommandText = query;
        command.CommandType = CommandType.Text;

        return dbReader = command.ExecuteReader(CommandBehavior.CloseConnection);
    }

    private void btn1_Click(object sender, EventArgs e)
    {
        try
        {  
            string query = $"insert into schule.schule(id,name,schuler,adresse,baujahr) values('{IdTextBox.Text}','{NameTextBox.Text}','{SchulerTextBox.Text}','{AdresseTextbox.Text}','{BaujahrTextbox.Text}');";
            using DbDataReader dbReader = ExecuteQuery(query);
            MessageBox.Show("Save Data");
            while (dbReader.Read())
            {
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btn2_Click(object sender, EventArgs e)
    {
        try
        {
            string query = $"update schule.schule set id='{IdTextBox.Text}',name='{NameTextBox.Text}',schuler='{SchulerTextBox.Text}',adresse='{AdresseTextbox.Text}',baujahr='{BaujahrTextbox.Text}' where id='{IdTextBox.Text}';";
            using DbDataReader dbReader = ExecuteQuery(query);
            MessageBox.Show("Data Updated");
            while (dbReader.Read())
            {
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btn3_Click(object sender, EventArgs e)
    {
        try
        {
            string query = $"delete from student.studentinfo where id='{IdTextBox.Text}';";
            using DbDataReader dbReader = ExecuteQuery(query);
            MessageBox.Show("Data Deleted");
            while (dbReader.Read())
            {
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    private void btn4_Click(object sender, EventArgs e)
    {
        try
        {
            string MyConnection2 = "datasource=127.0.0.1;port=3306;username=root;password=;";
            //Display query  
            string Query = "select * from schule.schule;";
            MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
            //  MyConn2.Open();  
            //For offline connection we weill use  MySqlDataAdapter class.  
            MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
            MyAdapter.SelectCommand = MyCommand2;
            DataTable dTable = new DataTable();
            MyAdapter.Fill(dTable);
            dg1.DataSource = dTable; // here assign dTable object to the dataGridView1 object to display data.               
                                     // MyConn2.Close();  
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}

So by using the Factory pattern we are making the creation of db connections easily reusable throughout the program not just here. Probably over kill for you at this stage but I wrote it and then thought of that after. You could have just stored the connection string at a higher level, such as in the config files and reused it from there. This factory class needs to be injected into the Form1’s constructor, this is going to be done with a container, there are many options out there but look into Inversion of Control containers and dependency injection for tutorials etc on how to implement this. But again, the easy way would be to just get it from the config files using the ConfigurationManager and adding it to the config that was probably produced by the project template. If there isn’t one/you didn’t use a template then you’ll need to make one and add the connection string section/properties. A quick google will find you some copy paste examples.

The next thing that I’ve done is taken the repeated logic for creating a connection, and a command and put it into a separate method. Really this should be pulled out into another class etc but to keep it simple I left it in the Form1 class.

I’ve not manually opened and closed the connections, I’ve used the using keyword to do this for me, it is good because even in the event of an error it will still dispose of the resource.

If you wanted to go silly you could move everything into a single method but that’ll bite you later as it grows and you want more unique logic between buttons.

I’ve also used string interpolation in the string ($"{variablename}") for the strings rather than concatenation ("" + variablename + “”) as it saves some space and makes it easier to read. You may want to create some sort of constants class for those variables if you think you will need to reuse the same queries.

Note, this is using C# 8 syntax if you are using C# 7 then the code will not compile, you’ll have to change the using declaration in to a statement.