Step 1:
Drag GirdView from Toolbox on your design page.
Step 2:
Check out the code of aspx page. It will be something like this
<asp :GridView
ID="GridView1″
runat="server">
</asp:GridView>
Step 3:
Now add one bound column, this way
<asp
:GridView ID="GridView1″
runat="server"
AutoGenerateColumns="false">
<columns>
<asp
:BoundField HeaderText="ColumnName"
DataField="ColumnName"
/>
</columns>
</asp:GridView>
Note: Set the AutoGenerateColumns to false.
Note: HeaderText="ColumnName" is the name appearing as column heading in
gridview.
Note: DataField="CoumnName" is the name of column returning from the
SELECT query result.
Step 4:
You can add one or more bound columns also
<asp
:GridView ID="GridView1″
runat="server"
AutoGenerateColumns="false">
<columns>
<asp
:BoundField HeaderText="ColumnName"
DataField="DataColumnName"
/>
<asp
:BoundField HeaderText="ColumnName"
DataField="DataColumnName"
/>
<asp
:BoundField HeaderText="ColumnName"
DataField="DataColumnName"
/>
</columns>
</asp:GridView>
Step 5:
Example: Say your code behind class contains -
{
Strinf sql = "SELECT emp_name,emp_id,emp_salary,emp_email FROM .......";
SqlDataAdapter ad = new SqlDataAdapter(sql,connectionObject);
DataSet ds=new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Now, in some situations you want some additional columns to retrieve for later
use.
But, while binding the DataSet to GridView you want to display limited columns.
Here, you retieve columns: emp_name,emp_id,emp_salary and emp_email
But, you dont want to display email in gridview but want to use it in your code
behind class somewhere.
So, you need to set the AutoGenerateColumns = false.
Then, you need to bound the columns which you want to bind to gridview.
<asp
:GridView ID="GridView1″
runat="server"
AutoGenerateColumns="false">
<columns>
<asp
:BoundField HeaderText="Employee
Name" DataField="emp_name"
/>
<asp
:BoundField HeaderText="Employee
Id" DataField="emp_id"
/>
<asp
:BoundField HeaderText="Salary"
DataField="emp_salary"
/>
</columns>
</asp:GridView>
Step 6: Run the application
Result would be:
Employee Name
|
Employee Id |
Salary |
Suresh Paldia |
3625132 |
25000 |
Himanshu Bhardwaj |
2564125 |
25632 |
Kamal Gupta |
4125452 |
25654 |
And DataSet still contains emp_email which is
not bound to gridview but can be retrieved out of dataset and use
Happy Learning...