Data Bind With DataGridView in C#
PART-1
Step :- 1
Create A Windows Form Application. Then Design Form Like this Image.
Step :- 2
Write the Code for the "ADD" button
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
SqlConnection _cON = new SqlConnection("Data Source=.;Initial Catalog=VickyRajBlogs;Integrated Security=True");
_cON.Open();
SqlCommand _cMD = new SqlCommand("Insert into Customer values('" + txtName.Text + "','" + txtAge.Text + "'," + txtContactNo.Text + ")", _cON);
int res = _cMD.ExecuteNonQuery();
_cON.Close();
}
catch (Exception ex)
{
MessageBox.Show("ERROS" + ex.ToString());
}
finally
{
txtName.Text = string.Empty;
txtAge.Text = string.Empty;
txtContactNo.Text = string.Empty;
//Method "showAll()"
showAll();
}
}
Write the Code for the "SHOW" button
private void btnShow_Click(object sender, EventArgs e)
{
try
{
showAll();
}
catch (Exception ex)
{
MessageBox.Show("ERROS" + ex.ToString());
}
}
Write the Code for the "SHOW" Method
private void showAll()
{
SqlConnection _cON = new SqlConnection("Data Source=.;Initial Catalog=VickyRajBlogs;Integrated Security=True");
_cON.Open();
SqlCommand _cMD = new SqlCommand("Select * from Customer", _cON);
SqlDataAdapter _sDA = new SqlDataAdapter(_cMD);
DataTable _dT = new DataTable();
_sDA.Fill(_dT);
DataGridView1.DataSource = _dT;
_cON.Close();
}
Write the Code for the "CANCEL" Method
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
Write the Code for the "Load Event"
private void Form1_Load(object sender, EventArgs e)
{
showAll();
}
PART-2
Write the Code for the "Customer" Table
Create Table Customer
(
SrNo int IDENTITY(1,1) Primary Key ,
Name nvarchar(50),
Age nvarchar(50) ,
ContactNo nvarchar(50)
)
Write the Code for the "SELECT" Query
Select * from Customer
Write the Code for the Add Values into "Customer" Table
Insert into Customer values('VICKY',21,9654388184)
No comments:
Post a Comment