Sunday, January 17, 2010

Using Mysql with C#.NET:



Pre-Requiste:
1)create a datbase in mysql with name say ‘sangram’
2)create atable in it namely ‘course’ with columns ‘cno’ as in and ‘cname as varchar(20)
3) add some record into it
4) now create c# window application with datagridview and to command button one for loading data other for exiting application
5) put following code

CodeBehind :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace mysqldemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void LoadGuests()
{
try
{
//create a new mysqlconnection
MySqlConnection mycon=new MySqlConnection("datasource=localhost;username=root;password=root;database=sangram");
mycon.Open();

//creating mysql adapter
MySqlDataAdapter myadp = new MySqlDataAdapter("select * from course", mycon);

//create dataset
DataSet myds = new DataSet();

//now fill and bind the datagrid
myadp.Fill(myds, "course");
dataGridView1.DataSource = myds.Tables["course"].DefaultView;



}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}

}

private void button2_Click(object sender, EventArgs e)
{
this.Close();
}

private void button1_Click(object sender, EventArgs e)
{
LoadGuests();
}

}
}

No comments:

Post a Comment