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.
Related
So I have a GridView for a C# web application, that has a Buttonfield, and when that button is clicked, I need to get the value of one of the fields for that row and store it in a variable for processing in some way.
However, neither the GridView nor the ButtonField seem to possess any means of doing this.
Can anyone recommend a way of getting data from a GridView, or if this is not possible, a different type of view that does offer this functionality, while still displaying a whole table (eg, not a DetailsView)
You can Check this link: https://msdn.microsoft.com/en-us/library/bb907626(v=vs.140).aspx.
Define the CommandName of the Button.
In the GridView Define the RowCommand Event and Check the CommandName.
Get the Index of the Row.
Get the Column with GridView.Rows[index](columnIndex)
If you are using asp:TemplateField like shown below then you can access the row content using RowCommand
Markup
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCode" runat="server" Text='<%# Eval("CustomerID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="AddCode" Text="Add New"/>
Code
protected void gvwSearch_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "AddCode")
{
var clickedButton = e.CommandSource as Button;
var clickedRow = clickedButton.NamingContainer as GridViewRow;
var rows_lblCode = clickedRow.FindControl("lblCode") as Label;
// now you can acccess all the label properties. For example,
var temp = rows_lblCode.Text;
}
}
I have a GridView that draws fields from a dataset:
protected void Page_Load(object sender, EventArgs e)
{
var dat = SecurityManager.GetAllGroups();
GridView1.DataSource = dat;
GridView1.DataBind();
}
One of these is the IsAdministrator property.
It should show up as a checkbox.
It does, but it is grayed out. I want it to be enabled so I can modify it.
From there, I will go through each row and update accordingly.
Is this possible to do? How can I ungray the checkbox?
Thanks
If you are using the CheckBoxField, you can only change the value when in edit mode. To workaround this, if you want a checkbox for all rows, use the TemplateField, and supply a checkbox in the item template like:
<asp:TemplateField ..>
<ItemTemplate>
<asp:CheckBox .. Checked='<%# Bind("IsAdministrator") %>' />
</ItemTemplate>
</asp:TemplateField>
I have a column in my gridview which displays the total cost of certain items which is pulled from my database table. However, my users also have a currency information attached to their account. What I would like to do is convert this column based on the individual user's currency info. I have tried the following:
<asp:HiddenField id="currencyconvfactor" runat="server" />
<asp:TemplateField HeaderText="Total" SortExpression="Total">
<ItemTemplate>
<%# currencyconvfactor.Value %> //this is just a test. see below for the issue.
</ItemTemplate>
</asp:TemplateField>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
currencyconvfactor.Value = 12345
//i simplified retrieving the specific factor value here as I do some database commands to pull the specific value
}
However, I notice that the template field column is always empty. Does that mean that the gridviews are generated before the page load event? If so, how could I perform the column conversions on the first page load? More specifically, how can I access the conversion factor to perform the conversion in time?
You may want to look at using a RowDataBound event to access the column and do whatever computation you need:
.aspx:
<Columns>
<asp:TemplateField HeaderText="Template Field">
<ItemTemplate>
<asp:Label ID="lblConvValue" Runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Code-behind:
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Get the current row's data
DataRowView rowView = (DataRowView)e.Row.DataItem;
// Do your conversion
var conv = int.Parse(rowView["valueToConvert"].ToString());
var converted = conv * 12345; // Whatever conversion you want.
// Set the value of the control in the ItemTemplate
Label lblConvValue= (Label)e.Row.FindControl("lblConvValue");
lblConvValue.Text = converted.ToString();
}
}
If all rows use the same Currency conversion factor, you can do the following.
...
<ItemTemplate>
<%#GetCurrencyconvfactor()%>
</ItemTemplate>
...
In the code behind define a method to return the value
public string GetCurrencyconvfactor()
{
//you can also pass in custID as an argument if each row uses different factor
return "123"; // or get this from the user profile/settings
}
After defining the values, call GridView.DataBind()
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"
I have two GridView in ASP.net 3.5 page. I have HyperLink field as one of the fields in the First GridView.
On click of this hyperlink I need to call display the 2nd grid by passing some values to a method showAllRecords(value from hyperlink)
How do I do this?
Thanks
You can try a TemplateField like this for GridView1 (primary GridView)
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="LinkButton1" CommandName="cmdName" CommandArgument='<%# Eval("IdColumn") %>' > LinkButton</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
and in GridView1's RowCommand, you can get the CommandArgument and setup the DataSource for GridView2 (child GridView).
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName = "cmdName")
{
var arg = e.CommandArgument;
// use arg to filter GridView2's DataSource
GridView2.DataSource = FilteredDataSource;
GridView2.DataBind();
// show GridView2 if it's hidden.
}
}
Maybe the following blog post could give you a hint;
http://www.tugberkugurlu.com/archive/parent-child-view-in-a-single-table-with-gridview-control-on-asp-net-web-forms
First you need to handle SelectedIndexChanged event on the first grid and then get the value from the hyperlink. Is the hyperlink a DataKey? If it is then you get it by GridOne.SelectedDataKey.Values["key"] otherwise get the actual cell by valuefromGridOne = GridOne.SelectedRow.Cells[num].Text where number is the cell number. Once you have it you can pass the value to your second grid by handling Selecting event of the objectDataSource (assuming you use it to bind data) and passing the value like this e.InputParameters["dataKey"] = valuefromGridOne;