Hi manishvad,
Simply take gridview without assigning column and then bind the datatable or dataset to gridview. Thats all.
I have created sample. Refer the below code.
For this sample I have used of NorthWind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:GridView runat="server" ID="gvCustomers" />
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvCustomers.DataSource = GetDataTable("SELECT TOP 5 CustomerID,CompanyName,ContactName FROM Customers", CommandType.Text);
gvCustomers.DataBind();
}
}
private DataTable GetDataTable(string query, CommandType commandType)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = commandType;
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
gvCustomers.DataSource = GetDataTable("SELECT TOP 5 CustomerID,CompanyName,ContactName FROM Customers", CommandType.Text)
gvCustomers.DataBind()
End If
End Sub
Private Function GetDataTable(query As String, commandType As CommandType) As DataTable
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.CommandType = commandType
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Using
End Function
Query
SELECT TOP 5 CustomerID,CompanyName,ContactName FROM Customers
SELECT TOP 5 CustomerID,ContactName,Address,City,Country FROM Customers
Screenshot
