How to make gridview column visible true or false dynamically? - c#

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;
}

Related

How to get a CheckBoxField from a DetailsView

I have been trying to figure this out for hours. So sad! The structure of my ascx is like
<asp:DetailsView ...>
<Fields>
.
.
<asp:CheckBoxField DataField="ThingEnabled" HeaderText="Thing Enabled"/>
.
.
.
</Fields>
</asp:DetailsView>
and the element I want is the ThingEnabled one.
Setup:
DetailsView dv = (DetailsView)sender;
CheckBoxField cbf = ????
Note that CheckBoxFields do not have ID properties, so I can't use FindControl.
Note that DetailsView uses cells on it instead of control IDs for each row it has, hence you can get CheckBoxField value using row, cell and control position like this:
// Page_Load is just an example event here, change to any event you need
protected void Page_Load(object sender, EventArgs e)
{
DetailsView dv = sender as DetailsView;
// the checkbox uses checked state as its value to be passed
// n = row/cell/control indexes where CheckBoxField has bound into, starting from 0
// e.g. dv.Rows[0].Cells[0].Controls[0] as CheckBox
bool checkboxvalue = (dv.Rows[n].Cells[n].Controls[n] as CheckBox).Checked;
}
If you still want using FindControl, use ItemTemplate wrapper element and create a CheckBox control on it (note that you may need to use a BoundField with DataField="ThingEnabled" on top of TemplateField for data binding):
<asp:DetailsView runat="server" ...>
<Fields>
...
<asp:TemplateField HeaderText="Thing Enabled">
<ItemTemplate>
<asp:CheckBox ID="ThingEnabled" runat="server" Checked="<%# Bind("ThingEnabled") %>">
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
Then you can access that checkbox control using FindControl:
DetailsView dv = sender as DetailsView;
// n = row/cell indexes, starting from 0
bool checkboxvalue = (dv.Rows[n].Cells[n].FindControl("ThingEnabled") as CheckBox).Checked;
References/similar issues:
How to get value from DetailsView Control in ASP.NET?
Get the value of a BoundField from a DetailsView
Accessing DetailsView check box value
Its also possible to use linq to get any field within a DetailsView in this way.
// Page_Load is just an example event here, change to any event you need
protected void Page_Load(object sender, EventArgs e)
{
DetailsView dv = sender as DetailsView;
//using linq to get the CheckBoxField control
var field = dv.Fields.Cast<DataControlField>().Single(x => x.HeaderText == "TitleOfCheckboxField") as CheckBoxField;
}

Pass Gridview one Row TextBox value To Another Row Textbox Value

I have Gridview with 10 Rows each row have 2 columns which is Textbox and Checkbox.
what i have to do is have to enter textbox Value as 1000 and i Clicked the Checkbox at first Row then value must go to Textbox of Second row and i clicked checkbox of Second Row then value must be go to third row of Textbox and so on.
i tried this,
protected void txtintroId_TextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow grid = ((GridViewRow)txt.Parent.Parent.Parent);
TextBox txtIntro = (TextBox)txt.FindControl("txtintroId");
}
here i get the 1st row Value but How do i pass this to second Row.
Assist me
Here is full working code(as per your requirement )
Create a gridview like this
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("txtcolumn") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox2_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Add a function in code behind C#
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
int rowNo=0;
foreach (GridViewRow GV1 in GridView1.Rows)
{
rowNo++;//
if (rowNo < GridView1.Rows.Count) //Checking that is this last row or not
{
//if no
CheckBox chkbx= (CheckBox)GV1.FindControl("CheckBox1");
TextBox curenttxtbx = (TextBox)GV1.FindControl("TextBox1");
if (chkbx.Checked == true )
`{
int nextIndex = GV1.RowIndex + 1;//Next row
TextBox txtbx = (TextBox)GridView1.Rows[nextIndex].FindControl("TextBox1");
txtbx.Text = curenttxtbx.Text;
}
}
//if yes
else
{
//For last row
//There is no next row
}
}
}
And i used this data table as data source
DataTable table = new DataTable();
table.Columns.Add("txtcolumn", typeof(string));
table.Rows.Add("1");
table.Rows.Add("32");
table.Rows.Add("32");
table.Rows.Add("32");
table.Rows.Add("3");
table.Rows.Add("32");
table.Rows.Add("32");
I tested this code it is working as per your requirement. (And SORRY for this bad formatting. i will do it later or please some body correct the formating :))

How to assign correct serial No. no in paged GridView?

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.

bind gridview dynamically with label and tooltip

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.

.NET GridView - Can you right-align just one column?

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"

Categories

Resources