Sunday 20 April 2014

Show database value in DataGridView in window application


                                                                                                                                             Previous..
                                                                                                                                                Next..

Here i will explain that how to show Database value in DataGrid View.

Step(1): Form
Drag and down a data Gridview and a Button from tool box.
Step(2): Code
Now click on Botton (Load Button). and write this code

 private void Load_button_Click(object sender, EventArgs e)
    SqlConnection con = new SqlConnection("server = MUNESH;Database=datastore;UID=sa;Password=123;");
    SqlCommand cmd = new SqlCommand("Select * from data1", con);
    try
   {
        
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        DataTable dt = new DataTable();
        da.Fill(dt);
      BindingSource bsource = new BindingSource ();
   
    bsource .DataSource = dt;
        dataGridView1.DataSource = bsource ;
       
    }
    catch (Exception ec)
   {
        MessageBox.Show(ec.Message);
   }

If you Don't want to load data in datagrid view at button click then you can make function for filling this datagridview.

public void displayDataGridView()
{
    SqlConnection con = new SqlConnection("server = MUNESH;Database=datastore;UID=sa;Password=123;");
    SqlCommand cmd = new SqlCommand("Select * from data1", con);
    try
   {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource = dt;
        con.Close();
    }
    catch (Exception ec)
   {
        MessageBox.Show(ec.Message);
   }


Step(3): Run
Now run your application.
                                                                                                                                             Previous..
                                                                                                                                                Next..

No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...