Monday, May 28, 2012

Display Data into DataGridView using DataTable in C#

By the following code we can display data into Data Grid View using datatable.

private void btnShow_Click(object sender, EventArgs e)
{
        this.Cursor = Cursors.WaitCursor;
        if (myConnection.State.Equals(ConnectionState.Closed))
                myConnection.Open( ); // Here
myConnection is a SQL Connection object

    string selectQry = "SELECT P.PECODE, P.PENAME, P.PDEPNM, P.PSECNM, ";
    selectQry += "D.DDSGDS, P.SHFTNM ";
    selectQry += "FROM PIDT00V P INNER JOIN DDSG00V D ON P.PDESIGCD = D.DDSGCD ";
    selectQry += " WHERE (P.PCOMCD = '" + ComCode + "') ";
    selectQry += " ORDER BY P.PECODE";
    
    SqlCommand dbcommand = new SqlCommand(selectQry, myConnection);

    dataGridView1.DataSource = null;
    dataGridView1.Columns.Clear();
    DataTable datatable = new DataTable();

            DataColumn dcol0 = new DataColumn("PECODE", typeof(System.String));
            DataColumn dcol1 = new DataColumn("PENAME", typeof(System.String));
            DataColumn dcol2 = new DataColumn("PDEPNM", typeof(System.String));
            DataColumn dcol3 = new DataColumn("PSECNM", typeof(System.String));
            DataColumn dcol4 = new DataColumn("DDSGDS", typeof(System.String));
            DataColumn dcol5 = new DataColumn("SHFTNM", typeof(System.String));           

            datatable.Columns.Add(dcol0);
            datatable.Columns.Add(dcol1);
            datatable.Columns.Add(dcol2);
            datatable.Columns.Add(dcol3);
            datatable.Columns.Add(dcol4);
            datatable.Columns.Add(dcol5);           

            DataRow drow;
            dbreader = dbcommand.ExecuteReader();

            while (dbreader.Read())
            {
                drow = datatable.NewRow();

                drow["PECODE"] = dbreader[0];
                drow["PENAME"] = dbreader[1];
                drow["PDEPNM"] = dbreader[2];
                drow["PSECNM"] = dbreader[3];
                drow["DDSGDS"] = dbreader[4];
                    drow["SHFTNM"] = dbreader[5];
               
               datatable.Rows.Add(drow);
            }
            dbreader.Close( );

            dataGridView1.DataSource = datatable;

            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.ReadOnly = true;
            dataGridView1.RowHeadersVisible = false;

            this.Cursor = Cursors.Default;
}

3 comments:

  1. this nice example

    we are thanks for this owner

    my self Vijay Movaliua ( vijay.comp@gmail.com) (www.imagicsolution.com)

    ReplyDelete
  2. great work brother...thanx so much : guddu

    ReplyDelete