Refresh DataGridView from another Form in C# windows

Hi there,
You can use custom events in this situation, you can try the sample below.


Form1:
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static SqlConnection getc()
        {
            string sqlstr = "Data Source=.;Initial Catalog=pp1;Integrated Security=True";
            SqlConnection conn = new SqlConnection(sqlstr);
            return conn;
        }
        private DataTable GetData()
        {
            DataTable dt = new DataTable();
            using (SqlConnection conn = getc())
            {
                SqlCommand cmd = new SqlCommand("select * from dgv", conn);
                conn.Open();
                SqlDataAdapter ad = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                ad.Fill(ds);
                dt = ds.Tables[0];
                return dt;
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = GetData();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 fm = new Form2();
            fm.RefreshDgv += new Form2.DoEvent(fm_RefreshDgv);
            fm.Show();
        }

        void fm_RefreshDgv(string a, string b, string c)
        {
            using (SqlConnection conn = getc())
            {
                SqlCommand cmd = new SqlCommand("insert into dgv values(@a,@b,@c)", conn);                
                cmd.Parameters.AddWithValue("@a", a);
                cmd.Parameters.AddWithValue("@b", b);
                cmd.Parameters.AddWithValue("@c", c);
                conn.Open();
                cmd.ExecuteNonQuery();
                dataGridView1.DataSource = GetData();               
            }
            
        }
    }
 
Form2:
    public partial class Form2 : Form
    {
        public delegate void DoEvent(string a, string b, string c);
        public event DoEvent RefreshDgv;

        public Form2()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.RefreshDgv(textBox1.Text, textBox2.Text, textBox3.Text);
            this.Close();
        }   
    }


1 comment:

  1. C Duster: Refresh Datagridview From Another Form In C Windows >>>>> Download Now

    >>>>> Download Full

    C Duster: Refresh Datagridview From Another Form In C Windows >>>>> Download LINK

    >>>>> Download Now

    C Duster: Refresh Datagridview From Another Form In C Windows >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete