Home > OS >  How do I automatically reload the gridview after adding the new name?
How do I automatically reload the gridview after adding the new name?

Time:02-21

I have to automatically reload the gridview which contains the list of the brand names. What should be done to automatically reload the data gridview when the "Brand has been added" meessage is shown.I have the data gridview in another form.

public partial class AddBrand : Form
{
    SqlConnection cn = new SqlConnection();
    SqlCommand cm = new SqlCommand();
    DBConnection dbcon = new DBConnection();
    public AddBrand()
    {
        InitializeComponent();
        cn = new SqlConnection(dbcon.MyConnection());
    }
    private void Clear()
    {
        btnSave.Enabled = true;
        btnUpdate.Enabled = false;
        tbBrand.Clear();
        tbBrand.Focus();
    }

    private void BtnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (MessageBox.Show("Do you want to save this brand?", " ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                cn.Open();
                cm = new SqlCommand("INSERT INTO tblBrand(brand)VALUES(@brand)", cn);
                cm.Parameters.AddWithValue("@brand", tbBrand.Text);
                cm.ExecuteNonQuery();
                cn.Close();
                MessageBox.Show("Brand has been added.");
                Clear();
            }             
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {

    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        Brand brand = new Brand();
        brand.ShowDialog();
    }
}

This is the design:

enter image description here

CodePudding user response:

Hope as per your code Brand is the form showing GridView. In this form you can open the form AddBrand.

var addBrand = new AddBrand(); 
var result = addBrand.ShowDialog();
if(result  == DialogResult.Yes)
ReloadLogic()// you can read from db 

In BtnSave_Click event in Brand form you can write

this.DialogResult = DialogResult.Yes; Close();

CodePudding user response:

If you want to reload the datagridview when the "Brand has been added" meessage is shown, you can read data to datagridview again.

You can refer to the following code in the form containing datagridview:

private void Form1_Load(object sender, System.EventArgs e)
    {
        SqlConnection cn = new SqlConnection();
        SqlCommand cm = new SqlCommand();
        DBConnection dbcon = new DBConnection();
        cn = new SqlConnection(dbcon.MyConnection());
        cn.open();
        string sql = "select * from tblBrand";
        SqlDataAdapter sda = new SqlDataAdapter(sql, cn);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        dataGridView1.DataSource = ds.Tables[0];
        cn.close();
    }
  • Related