Hi! I have two form in c# windows application. In first form have datagridview and second form textbox for insert data into database. When I insert data from second form I must close first form and another start for show data from database in datagridiew. I want click save button second form then close it and show data in datagridview form without close first form. How I can do it?
https://imgur.com/a/nMRvcFX
USE [counterDB]
GO
/****** Object: Table [dbo].[tblInfo] Script Date: 04/25/2018 23:06:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblInfo](
[Id] [int] IDENTITY(1,1) NOT NULL,
[LastName] [nchar](20) NULL,
[Name] [nchar](20) NULL,
[Address] [nchar](20) NULL
) ON [PRIMARY]
GO
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsForms
{
public partial class Form1 : Form
{
public string dbPath = @"Data Source=User-PC;Initial Catalog=counterDB;Integrated Security=True";
public Form1()
{
InitializeComponent();
dataGridView1.Columns[0].DataPropertyName = "LastName";
dataGridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[1].DataPropertyName = "Name";
dataGridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[2].DataPropertyName = "Address";
dataGridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.DataSource = GetData();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.ShowDialog();
}
public DataTable GetData()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(dbPath);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "select lastname, name, address from tblInfo";
con.Open();
try
{
dt.Load(cmd.ExecuteReader());
}
catch
{ }
con.Close();
return dt;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsForms
{
public partial class Form2 : Form
{
public string dbPath = @"Data Source=User-PC;Initial Catalog=counterDB;Integrated Security=True";
public Form2()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
InsertData(textBox1.Text, textBox2.Text, textBox3.Text);
this.Close();
}
public void InsertData(string LName, string Name, string Address)
{
SqlConnection con = new SqlConnection(dbPath);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "insert into tblinfo(lastname, name, address)values('" + LName + "','" + Name + "','" + Address + "')";
con.Open();
try
{
cmd.ExecuteReader();
}
catch
{ }
con.Close();
}
}
}