Can you easily right-align just one column in a GridView?
I have this
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
It is bound to a DataTable (generated dynamically) that has many columns. I just want the 'Price' column to be right-aligned.
(Coming across this problem, I am wondering if I should be printing out HTML <table> instead of using a GridView. Using HTML I would have total control.)
Yes, you can, but I think if you have AutoGenerateColumns set to true (which it is by default) then you need to right align the column using the RowDataBound event. As a side note, if it's easier you can set AutoGenerateColumns to false and use BoundFields which will give you more formatting options and will probably eliminate the need for the RowDataBound event.
GridView:
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" runat="server"></asp:GridView>
Codebehind:
protected void GridView1_RowDataBound(object o, GridViewRowEventArgs e)
{
//Assumes the Price column is at index 4
if(e.Row.RowType == DataControlRowType.DataRow)
e.Row.Cells[4].HorizontalAlign = HorizontalAlign.Right;
}
Hope that helps.
<Columns>
...
<asp:BoundField DataField="Price" HeaderText="Price"
ItemStyle-HorizontalAlign="Right" ItemStyle-Width="80" />
...
</Columns>
Even though the question posted long ago, this might help someone you happens to end up at this page.
The answers given assume that the index of the column to which the alignment will be applied is known in advance or the columns are created at design time on the .aspx page; but this is not always the case.
For someone looking for a general solution in which the columns are auto generated and the index of column with header ‘Price’ not known in advance, here is a solution
protected void grData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int i = ((DataTable)((GridView)sender).DataSource).Columns.IndexOf("Price");
for (int j = 0; j < e.Row.Cells.Count; j++)
{
if (j == i)
e.Row.Cells[j].HorizontalAlign = HorizontalAlign.Right;
else
e.Row.Cells[j].HorizontalAlign = HorizontalAlign.Left;
}
}
}
Enclose the item in the ItemTemplate in a div and then set styling to the div.
<ItemTemplate>
<div id="divReportName">
<asp:Label ID="lblReport" runat="server" ></asp:Label>
</div>
</ItemTemplate>
// css for div
#divReportName { text-align: left;}
You can perform alignment within the Boundfield using ItemStyle-
like this :
<asp:BoundField DataField="SOH" HeaderText="SOH" SortExpression="SOH" ItemStyle-HorizontalAlign="Right"/>
This worked for me where i needed to align only specific columns in my gridview
Did you add this in the first line of the GridView?
OnRowDataBound="GridView1_RowDataBound"
Related
I am using GridView in asp.net like this:
mygrid.DataSource = dTable;
mygrid.DataBind();
if (mygrid.Columns.Count > 1)
{
mygrid.Columns[2].Visible = false;
}
my grid view code is as follows
<asp:GridView ID="mygrid" runat="server" AllowPaging="True"
onpageindexchanging="mygrid_PageIndexChanging" PageSize="15"
PersistedSelection="true"
ondatabound="mygrid_DataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="Edit" runat="server" Text="Edit" NavigateUrl='<%# Eval("Value", "~/myweppage.aspx?Id=M{0}") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings PageButtonCount="4" />
</asp:GridView>
Here I am not able to set visible=false.
I tried with the following answer
How do I make several gridview columns invisible dynamically?
I am not finding datarow event in Visual Studio 2010. Can anyone help me to set the column visible property?
my Column structure of data table is
column[0] is Value column then 4 other columns are there.
my Column structure of Grid view is
column[0] is link field
column1 is Value field from Dtable
4 other columns
This is perfect solution for dynamically generated columns in gridview
Please try this :
int indexOfColumn = 1; //Note : Index will start with 0 so set this value accordingly
protected void mygrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells.Count > indexOfColumn)
{
e.Row.Cells[indexOfColumn].Visible = false;
}
}
For .aspx page edit gridview tag as follow :
<asp:GridView ID="mygrid" runat="server" AllowPaging="True"
onpageindexchanging="mygrid_PageIndexChanging" PageSize="15"
PersistedSelection="true"
ondatabound="mygrid_DataBound"
OnRowDataBound="mygrid_RowDataBound">
Here is the simple answer. Create css as below
.classHide{ display:none }
then instead of column.visible = false, just assign classHide CSS class to the column.
e.g.
grdRole.Columns(0).ItemStyle.CssClass = "classHide"
grdRole.Columns(0).HeaderStyle.CssClass = "classHide"
*strong text*Try to make use of the event ItemDataBound event and try the following syntax to hide the column dynamically:
mygrid.Columns[1].Visible = false //(Example)
Column count for a datatable starts from 0 not from 1 . so if it is the second column , you want to hide, index should be 1.
Hope this helps..
right Click on gridview and select Properties then select Events you will find there RowDataBound Double Click on it and in Row data bound write this
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
}
Try this:
for (int i = 0; i < YourGrid.Rows.Count; i++)
{
(YourGrid.Columns[2]).Visible = false;
}
If I write the below code, the gridview shows the content but the serial no (S.N.) starts from 1 again in the second page.
The data is called through Custom Component(.DLL).
How to solve this?
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
DataTable dt = new DataTable();
MMSLAYER.BLL.ReportBLL rb = new ReportBLL();
dt = rb.atmservicing(Convert.ToInt32(ddlServiceBy.SelectedValue),
Convert.ToDateTime(txtDateFrom.Text), Convert.ToDateTime(txtDateTo.Text));
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
ViewState["dtList"] = dt;
}
It seems to me as if you are printing (S.N) with the help of following code:
e.Row.RowIndex
Instead of this, try the following line of code:
e.Row.DataItemIndex
Ofcourse, this should be in your gridview row-databound event.
In Source view, set the AllowPaging attribute of the element to true, as in the following example:
<asp:GridView Runat="server" ID="GridView1" AllowPaging="true" />
You can set the size of your page to specify how many rows are displayed at once. In addition, you can set the style of the links used to create navigation buttons. You can choose from the following types:
Next and previous buttons. The button captions can be any text you want.
Page numbers, which allow users to jump to a specific page. You can specify how many numbers are displayed; if there are more pages, an ellipsis (...) is displayed next to the numbers.
To change the number of rows displayed per page
Select the GridView control, and in the Properties window, set PageSize to the number of rows you want to display per page.
To specify default paging with Next and Previous buttons
Set the GridView control to allow paging.
In the Properties window, expand the PagerSettings node.
Set Mode to NextPrevious.
Add OnRowDataBound="GridView1_RowDataBound" inside your GridView declaration:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" ....>
Add TemplateField inside your GridView:
<asp:TemplateField HeaderText="Serial number">
<ItemTemplate>
<asp:Label ID="lblSerial" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Add this in .cs file
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblSerial = (Label)e.Row.FindControl("lblSerial");
lblSerial.Text = ((GridView1.PageIndex * GridView1.PageSize) + e.Row.RowIndex + 1).ToString();
}
}
Try the follownig with the template field:
<asp:TemplateField>
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
It seems to me as if you are printing (S.N) with the help of following code:
' runat="server"/>--%>
Instead of this, try the following line of code:
' runat="server"/>--%>
It seems to me as if you are printing (S.N) with the help of following code:
<asp:Label ID="lblslno" Text='<%# Container.DisplayIndex + 1 %>' runat="server"/>
Instead of this, try the following line of code:
<asp:Label ID="lblslno" Text='<%# Container.DataItemIndex + 1 %>‘ runat="server"/>
Note the use of DataItemIndex instead of DisplayIndex.
This is how I navigate to myPage.aspx ,
Show Each
Show All
And I have a gridview in myPage.aspx
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:BoundField HeaderText="ColumnOne" Visible="true"/>
<asp:BoundField HeaderText="ColumnTwo" Visible="true"/>
</Columns>
</asp:GridView>
What I want to do is , if Query String is equal to all(~/myPage.aspx?show=all) , I want to set GridView1's Column2's visible to true , else , set visible to false .
How can I do it ?
You can use gridview pre-render method to set this...
protected void GridView_PreRender(object sender, EventArgs e)
{
if(Reqest.QueryString["Id"]=="all"&& Reqest.QueryString["Id"]!=null)
{
GridViewId.Columns[1].Visible = true;
}
else
GridViewId.Columns[1].Visible = false;
}
you can use gridview column index to hide the particular column
Code could be
if(Request.QueryString.Get("show")=="all")
GridView1.Columns[1].Visible=true;
else
GridView1.Columns[1].Visible=false;
More detail
GridView Hide Column by code
Edit 3
Settings in ASPX/ASCX can not be done directly.
<%= %> outputs directly to the response stream, and the asp markup is not part of the response stream. Its a mistake to assume the <%= %> operators are performing any kind of preprocessing on the asp markup.
More explanation
Why will <%= %> expressions as property values on a server-controls lead to a compile errors?
Edit 1
I think yes
<asp:BoundField HeaderText="ColumnTwo"
Visible='<% if (Request.QueryString.Get("all") == "all" ) "true" else "false" %>'/>
You will have to check for the syntex
Edit 2
Try this
Visible='<% Request.QueryString.Get("all") == "all"? "true": "false"%>'
Dear try to use RowDataBound event of Grid View like
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//here apply your condition
if(Request.QueryString["name"] == "all")
e.Row.Cells[<index_of_cell>].Visible = true;
else
e.Row.Cells[<index_of_cell>].Visible = false;
}
}
Try something like that.
Hope it works for you.
i want to bind gridview with datatable in code behind and i want to add label in each cell in gridview and display a tooltip on label of their values... i am not getting tool tip..
(i want to display an each seat of thatre stage) !!! and want to tooltip of it,and my stage
may change,so i want dynamically)
help me.. my code is here
//Grid view is bind on page load
it gives me Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < table.Rows.Count; i++)
{
for (int j = 0; j < table.Columns.Count; j++)
{
Label lbl = new Label();
lbl.Text = GridView1.DataKeys[e.Row.RowIndex]["LabelText"].ToString();
lbl.ToolTip = GridView1.DataKeys[e.Row.RowIndex]["TooltipText"].ToString();
e.Row.Cells[0].Controls.Add(lbl);
}
}
}
You need to add the Label to a cell in each row of the GridView. I would suggest storing the information for the Label and the tooltip in the data key collection, and adding the label in the OnRowDataBound event.
Option 1:
EDIT: Added markup to show how to add data keys
Define the data keys like in the example below. Replace LabelTextColumn and TooltipTextColumn with the actual you want to use for the text and the tooltip. Also, notice how the OnRowDataBound event handler is set here:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="LabelTextColumn, TooltipTextColumn" OnRowDataBound="GridView1_RowDataBound" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
...
</Columns>
</asp:GridView>
EDIT: Corrected error using RowIndex to get data keys
Since you're in the RowDataBoundEvent, you don't need to use a loop. The RowDataBound event is called from within a loop as each row is databound, which is why you have access the current row with e.Row
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//we don't need this anymore, because the label is already in the row
//Label lbl = new Label();
//get the label from the row
Label lbl = (Label)e.Row.FindControl("Label1");
--set the text and tooltip text using the datakeys specified in the markup
lbl.Text = grd.DataKeys[e.Row.RowIndex]["LabelTextColumn"].ToString();
lbl.ToolTip = grd.DataKeys[e.Row.RowIndex]["TooltipTextColumn"].ToString();
//we don't need this anymore either, because the label is already added to the row
//e.Row.Cells[0].Controls.Add(lbl);
}
Option 2: Using inline Eval() function to set the text and tooltip text
<asp:GridView ID="GridView1" runat="server" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("LabelTextColumn")' Tooltip='<%#Eval("TooltipTextColumn")%>' />
</ItemTemplate>
</asp:TemplateField>
...
</Columns>
</asp:GridView>
When you databind, it destroys the current control collection and populates with the provided data source.
For your specific application, you would also need to attach to the GridView.RowCreated event and then insert the tooltip you need.
Implement this in a handler for the Gridview.RowDataBound Event.
I have three fields being displayed in the gridview. Depending on the value of first field, I have to either display or hide the second two fields.
The following code is what I've tried so far but I don't know how to get the full solution.
Could anybody have a look please?
The three fields are
1) activeStatus
2)DateMadeInactive
3)Comments
protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
bool activeStatus=Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem,"Active"));
if(activeStatus)
{
// I need to display the activeStatus columns
}
else
{
// I need to hide activeStatus Column and Display the DatemadeInactive and Comments
}
}
}
You can put conditionals into template fields:
<asp:GridView ... runat="server">
<Columns>
... your other fields ...
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label Text='<%# (bool)Eval("Active")
? Eval("activeStatus")
: Eval("DateMadeInactive", "Inactive since {0}") %>'
runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
What I gather from your question is you want to know how to hide or display any given column in a DataGridView. If so, you just need to add the column to the DataGridView, either with a DataSource or manually, and then hide any columns you don't want by doing the following:
dataGridView1.Columns["YourColumnName"].Visible = false;
I did something like this using, IIRC, the CellFormatting event. It gives you an opportunity to test the value of each cell and replace it or other cells in the row based on that. In my case I was replacing numeric values with looked-up strings and altering background color.