Can I apply unit conversion to a gridview column? - c#

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()

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

getting GridView data from buttonField press?

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

cell value in gridview is not getting in asp.net

im not getting the valu of specic row in row data bound event , value coming null;
<asp:TemplateField>
<HeaderTemplate>
Today's pos
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl_TodayPos" runat="server" Text='<%# Eval("CurrentPosition") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
aspx.cs code
protected void GrdKeyWord_RowCommand(object sender, GridViewCommandEventArgs e)
{
string value = GrdKeyWord.Rows[rowindex].Cells[5].ToString();
}
The value you are looking for is stored in a label control not in a table cell. Therefore, you need to use FindControl on that row to access the lbl_TodayPos:
Label myLabel = (Label)GrdKeyWord.Rows[rowindex].FindControl("lbl_TodayPos");
string value = myLabel.Text;
If you autogenerate the columns in the gridview, or if you used 'BoundField' (instead of TemplateField) you could use .Cells[]. Because, in this case, you would have gridview rendered as pure html table with table cells.

Change value of asp:BoundField as page loads

I have the following:
<Columns>
...
<asp:BoundField DataField="datetime_added" HeaderText="When Added" ReadOnly="True" SortExpression="datetime_added" />
...
</Columns>
The DataField datetime_added comes from a SQL Data Source. I want to do some editing of every value for this column after the values are queried from the SQL Data Source on the C# side. Kind of like:
//short pseudo code example
protected void someEvent(object sender, EventArgs e)
{
sender.GetField["datetime_added"] = "test";
}
Is there a way to do this?
use a templatefield instead of a boundfield
- with a label
- the label text is fed by a function throught something like this:
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%= SomeFunction(Eval("db_id"),Eval("description")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And this in your code behind:
protected string SomeFunction(object id, object description)
{
//your code
return "";
}
When your function is called, the field from SQL is passed as an object
so that you can use it if you want or return something else based on whatever you want.
The function is called when the value is bound from the datasource in each row, you'll probably need to pass an id as well to identify the row.
Have you tried the "OnRowCreated" event? I'm assuming here that you're using a GridView, and if not, then there may be something similar in whatever component it is you're binding the data to.
For GridView, here is an example:
protected void gridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// do what you need in here
// e.Row.Cells[x] where x = the column number
}
}
Also, this method can be really slow depending on how many rows you're processing.
If you are using RowDataBound event to manipulate the values before it's being bound to the grid (getting called while binding every row to the gridview)
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string datetimeadded = DataBinder.Eval(e.Row.DataItem, "datetime_added").ToString();
// or you can use the cell index to reference the boundfield like below
string datetimeadded = e.Row.Cells[1].Text;
}
}

Gridview -Problem

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.

Categories

Resources