Sunday, 1 December 2013

How to transpose one dataGridView to another dataGridView using Dataset and SqlDataAdapter

How to transpose one dataGridView to another dataGridView using Dataset and SqlDataAdapter 

Note: Transpose means interchanging. A matrix obtained from a given matrix by interchanging each row and the corresponding column. 

--Execute in SqlServer database…………………..

create table McaStudent(RollNo int primary key,Name nvarchar(50),MobileNo nvarchar(50))

insert into McaStudent values(1,'Udayan Maiti','07546345678')
insert into McaStudent values(2,'Kush Tiwari','09555484663')
insert into McaStudent values(3,'Naved Khan','09846345678')
insert into McaStudent values(4,'Ramu Gupta','09450325478')

--Code for From1.cs…………………..

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlDataAdapter da;
DataSet ds;

//Code for  bind  dataGridView1 with table

private void Form1_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("select * from McaStudent",@"Data Source=KUSH-PC\KUSH;Initial Catalog=College;User ID=sa;Password=tiwari");
ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];

}

//Code for  transpose one dataGridView to another dataGridView using Dataset and SqlDataAdapter

private void btntranspose_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataColumn dc = new DataColumn();
dt.Columns.Add(dc);
}
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
dr[j] = ds.Tables[0].Rows[j][i];

}
dt.Rows.Add(dr);
dataGridView2.DataSource = dt;
dataGridView2.ColumnHeadersVisible = false;
}

for (int i = 0; i < dt.Rows.Count; i++)
{
dataGridView2.Rows[i].HeaderCell.Value = ds.Tables[0].Columns[i].ColumnName;
}
}
}
}

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Please Check this link....
    http://dotnetinsimpleway.blogspot.in/2013/09/how-to-show-column-data-as-rows-with.html

    ReplyDelete
  3. wow itna tricky question solve kar diya bhai :)

    ReplyDelete