Wednesday, April 2, 2008

Working With Database in C#

This is a part of source code which works with DB.
Retreiving data from DB and displays in DataGid, also inserts data to DB.
Now you can develop how you want... :-)

...
public partial class Form1 : Form
{
private SqlConnection myConn = new SqlConnection ();
private SqlCommand myComm = new SqlCommand ();
private SqlDataAdapter myAdapter = new SqlDataAdapter ();
private DataSet myData = new DataSet();

private void Form1_Load(object sender, EventArgs e)
{
try
{
this.myConn.ConnectionString = " connection string ";
this.myConn.Open();
this.myComm = this.MyConn.CreateCommand();
this.myComm.CommandText= "SELECT * FROM test";
this.MyData.Clear();
this.myAdapter.Fill(this.myData, "test");

this.dataGridView1.DataSource = this.myData;
this.dataGridView1.DataMember = "test";
}
catch(Exception Ex)
{
MessageBox.Show(Ex.Message);
}
...
}

...

private void button1_click(object sender, EventArgs e)
{
try
{
this.myConn.ConnectionString = " connection string ";
this.myConn.Open();
this.myComm = this.MyConn.CreateCommand();
this.myComm.CommandText= "INSERT INTO test (name, nick) values('Boldbayar','Boogii')";
this.myComm.ExecuteNonQuery();
}
catch(Exception Ex)
{
MessageBox.Show(Ex.Message);
}
...
}

...


}
}

0 comments: