I need to add an specific text in an itemtemplate on a gridview...
right now I have this in my gridview
<asp:TemplateField HeaderText="Total" SortExpression="Total" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
in the part where it says
<asp:Label ID="lblTotal" runat="server" Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'>
I made an specific text, but it will always be the same text (well except in the Eval of course)... But I need to get the format I need from this method.
public static string GetFormatoMoneda(decimal decCantidad)
{
//Get data from currency (Dollars, Pesos, Euros, etc.)
DataRow dr = ConexionBD.GetInstanciaConexionBD().GetTipoDeMonedaPrincipal((int)HttpContext.Current.Session["Grupo"]);
return dr["Signo"] + Math.Round(decCantidad, 2).ToString("C").Substring(1) + " " + dr["Abreviatura"];
}
I use this method to get a specific string and use it on labels (I assign it on code on the cs file)..
But in this case... I have to insert that text on the column of a gridview...
How can I get that string value and insert it on a label inside of a templatefield/itemtemplate??
Instead of ...
Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'
...use
Text='<%#GetFormatoMoneda(Eval("Total"))%>'
However, this assumes that GetFormatoMoneda is in the same class as the web form. If not, then you need to include the class name, e.g.
Text='<%#MyClass.GetFormatoMoneda(Eval("Total"))%>'
Then you either need to make a change to GetFormatoMoneda to use an object type parameter, e.g.
public static string GetFormatoMoneda(object objCantidad)
{
var decCantidad = Convert.ToDecimal(decCantidad);
//Get data from currency (Dollars, Pesos, Euros, etc.)
DataRow dr = ConexionBD.GetInstanciaConexionBD().GetTipoDeMonedaPrincipal((int)HttpContext.Current.Session["Grupo"]);
return dr["Signo"] + Math.Round(decCantidad, 2).ToString("C").Substring(1) + " " + dr["Abreviatura"];
}
or use another method with an object parameter and call GetFormatoMoneda(decimal), passing in the correct value, such as
protected string CorrectFormat(object obj)
{
return GetFormatoMoneda(Convert.ToDecimal(obj));
}
in which case you would use
Text='<%#CorrectFormat(Eval("Total"))%>'
If you wanted to do it programmatically, this would work:
Default.aspx:
<asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvGrid_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Generate fake data
var data = Enumerable.Range(1, 20);
//Give the data to the grid
gvGrid.DataSource = data;
gvGrid.DataBind();
}
}
protected void gvGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the control
var lblTotal = (Label)e.Row.FindControl("lblTotal");
//Get the data for this row
var data = (int)e.Row.DataItem;
//Display the data
lblTotal.Text = data.ToString();
}
}
Related
I have a GridView and for one of the columns I'm using a drop down list that displays a list of users:
<asp:GridView style="float:left"
ID="gvBookings"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvBookings_RowDataBound"
DataKeyField="ID"
AutoGenerateColumns="false"
allowpaging="false"
<Columns>
<asp:BoundField DataField="FinishDate" HeaderText="Finish Date"></asp:BoundField>
<asp:TemplateField HeaderText="Time Spent By">
<ItemTemplate>
<asp:DropDownList id="ddlUsers" runat="server" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code behind I need to call a function that updates the database when the drop down list is changed. I have done this already for the FinishDate column so is there a similar way to do this for the drop down menu?
Code behind:
protected void gvBookings_RowDataBound(object sender, GridViewRowEventArgs e)
{
BHTaskClass.BookingTask booking = (BHTaskClass.BookingTask)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (TableCell c in e.Row.Cells)
{
if (count == 1)
{
string FinishTime = booking.FinishTime.HasValue ? booking.FinishTime.Value.ToString("hh':'mm") : "";
c.Text = "<input type=\"text\" id=\"txtFinishTime" + booking.ID + "\" style=\"width:70px\" type=\"text\" onblur=\"UpdateFinishTime(" + booking.ID + ",this.value)\" value=\"" + FinishTime + "\" >";
}
if (count == 2)
{
ddlUsers.SelectedValue = booking.TimeSpentName;
}
count++;
}
}
}
So when the FinishDate textbox is changed it calls the UpdateFinishTime function and this updates the database. How do I call a function for the drop down list?
ASPX
<asp:DropDownList id="ddlUsers" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="YourFunction_Changed">
</asp:DropDownList>
Code behind:
protected void YourFunction_Changed(object sender, EventArgs e)
{
//do stuff...
}
To get the Row ID you can do it as below
protected void YourFunction_Changed(object sender, EventArgs e)
{
//do stuff...
int Index = ((GridViewRow)((sender as Control)).NamingContainer).RowIndex;
// your logic follows based on the Index
}
In my web application, I have a grid-view and this grid-view is databounded. Above this grid-view, I have a text box where user can first enter the Employee ID and show the Employee Name in the grid view. In the grid view, it has the edit icon. When the user hit that edit icon, some text boxes in the grid view will appear and the use can edit the text in the text box. I got it working so far. However, my problem is when I am trying to edit the empty text box in the grid view, it gave me this error:
Object is not set to an instance of an object
All I did is to check if the text box is null. This does ignore the error but not really what I want
protected void txtEditedEmployeeID_TextChanged(object sender, EventArgs e)
{
DatabaseManager dbManager = Common.GetDbManager();
foreach (GridViewRow row in gridViewAddEmployee.Rows)
{
TextBox txtEmployee= (TextBox)row.FindControl("txtEmployeeID");
if (txtEmployee!= null)
{
string personID = txtEmployee.Text;
DataSet dsRE = dbManager.GetEmployeeNameByID(personID);
for (int i = 0; i < dsRE.Tables[0].Rows.Count; i++)
{
string employeeFirstName = dsRE.Tables[0].Rows[i]["FIRST_NAME"].ToString();
string employeeLastName = dsRE.Tables[0].Rows[i]["LAST_NAME"].ToString();
((TextBox)row.FindControl("txtEmployeeName")).Text = staffLastName + " " + staffFirstName;
}
}
else
{
}
}
}
HTML ASP.NET Code
<asp:TemplateField HeaderText="EmployeeID">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeID" runat="server" AutoPostBack="true" OnTextChanged= "txtEditedEmployeeID_TextChanged" Text='<%#Bind("Employee_ID") %>'Width="90px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeID" runat="server" CssClass="GridInput" Text='<%#Bind("Employee_ID") %>'Width="90px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Name">
<EditItemTemplate>
<asp:TextBox ID="txtEmployee" runat="server" ReadOnly ="true" Text='<%#Bind("Full_Name") %>'Width="90px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeName" runat="server" CssClass="GridInput" Text='<%#Bind("Full_Name") %>'Width="90px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
As on Edit txtEmployeeID will appear for that row only Not for all the rows of GridView and on TextBox Change event you are finding all row edited TextBox which is not appear till now so you may try this:
protected void txtEditedEmployeeID_TextChanged(object sender, EventArgs e)
{
DatabaseManager dbManager = Common.GetDbManager();
TextBox txt = sender as TextBox; // Edited TextBox
GridViewRow row = (txt.NamingContainer as GridViewRow);// Row of Edited TextBox
TextBox txtEmployee= (TextBox)row.FindControl("txtEmployeeID");
string personID = txtEmployee.Text;
DataSet dsRE = dbManager.GetEmployeeNameByID(personID);
for (int i = 0; i < dsRE.Tables[0].Rows.Count; i++)
{
string employeeFirstName = dsRE.Tables[0].Rows[i]["FIRST_NAME"].ToString();
string employeeLastName = dsRE.Tables[0].Rows[i]["LAST_NAME"].ToString();
((TextBox)row.FindControl("txtEmployeeName")).Text = staffLastName + " " + staffFirstName;
}
}
Try this:
Instead of
TextBox txtEmployee= (TextBox)row.FindControl("txtEmployeeID");
if (txtEmployee!= null)
{
string personID = txtEmployee.Text;
You should write it like this
TextBox txtEmployee = new TextBox();
txtEmployee = (TextBox)row.FindControl("txtEmployeeID");
if (!string.isNullorEmpty(txtEmployee.Text))
{
string personID = txtEmployee.Text;
I want to pass all the gridview value into another page
I have one gridview in PatientDetails.aspx page and one button as below
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="true" AutoGenerateSelectButton="true"
AutoGenerateDeleteButton="true" OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
<asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
<asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>"
SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" OnCommand="btnformatric_Command" />
on codebehind of PatientDetails.aspx is as below
protected void btnformatric_Click(object sender, EventArgs e)
{
if (gvDoctorList.SelectedRow != null)
{
Server.Transfer("Patientstaticformatrix.aspx");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
}
}
Now on the second page name Patientstaticformatrix.aspx the code behind is as below
protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.PreviousPage != null)
{
GridView gvDoctorList = (GridView)this.Page.PreviousPage.FindControl("gvDoctorList");
GridViewRow selectedRow = gvDoctorList.SelectedRow;
Response.Write("PatientId: " + selectedRow.Cells[0].Text + "<br />");
Response.Write("firstname: " + selectedRow.Cells[1].Text + "<br />");
Response.Write("lastname: " + selectedRow.Cells[2].Text + "<br />");
}
}
I had debug the code in second page....the value for gvDoctorList is null as well as the selectedRow is showing error of nullreference.
Can you please let me where I am wrong?
As i have seen your previous question also, So i can suggest you one thing, rather than keeping your gridview in session(which is expensive) you can use RowCommand event, and after having button here i don't think you need checkbox or chk_CheckedChanged event, you can pass the PatientID to your next page there you can write query to insert selected row data to your new table.
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged"
AutoPostBack="true" />
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'>
</asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='<%#
Eval("PatientId") %>' CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "select")
{
int pID = Convert.ToInt32(e.CommandArgument);
// either put ID in session and check
Session["PatientID"] = Convert.ToString(pID);
Server.Transfer("Patientstaticformatrix.aspx");
}
}
On page_Load Event
protected void Page_Load(object sender, EventArgs e)
{
string pID = Convert.ToString(Session["PatientID"]);
if(!string.IsNullOrEmpty(pID))
{
int patientID = Convert.ToInt32(pID);
//Call Stored procedure which will insert this record with this ID
// to another table
}
}
Try using Session Variables. You can set the GridView into a Session variable that can then be retreived later so long as the same session is still active.
You can use the following code to set the Session Variable on your first page :
Session["gvDoctorList"] = gvDoctorList;
And then to retreive from the variable on your second page :
GridView gvDoctorList = (GridView)Session["gvDoctorList"];
For more information on Sessions see the MSDN Session State Overview.
I have decided to add a second answer based on the correct comments from Ahmed, The session variables really shouldn't hold the amount of data of the gridview due to memory issues.
The following should work accordingly for what I assume you are doing :
Essentially when you are selecting the row to go to the next page you are trying to retrieve the data of that row onto the new page. Is this Assumption correct? If so then you have a number of options for you to use.
Again you could use the Session Variables to store the data of the row once extracted on the first page :
protected void btnformatric_Click(object sender, EventArgs e) {
if (gvDoctorList.SelectedRow != null) {
GridViewRow selectedRow = gvDoctorList.SelectedRow;
Session["PatientId"] = selectedRow.Cells[0].Text;
Session["firstname"] = selectedRow.Cells[1].Text;
Session["lastname"] = selectedRow.Cells[2].Text;
Server.Transfer("Patientstaticformatrix.aspx");
} else {
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
}
}
Essentially here you are on the first page and you get the data from the row. You then store this data in session variables and you can use the following to find the data from the next page :
protected void Page_Load(object sender, EventArgs e) {
if (this.Page.PreviousPage != null) {
//Retrieve values from Session Variables
Response.Write("PatientId: " + Session["PatientId"].ToString() + "<br />");
Response.Write("firstname: " + Session["firstname"].ToString() + "<br />");
Response.Write("lastname: " + Session["lastname"].ToString() + "<br />");
}
}
You also have a second option of using Query Strings to pass the data. Although for this method I believe you will have to change the Server.Transfer("Patientstaticformatrix.aspx"); to be Response.Redirect("Patientstaticformatrix.aspx");
Below is an example on using Query Strings :
protected void btnformatric_Click(object sender, EventArgs e) {
if (gvDoctorList.SelectedRow != null) {
GridViewRow selectedRow = gvDoctorList.SelectedRow;
//Create URL with Query strings to redirect to new page
Response.Redirect("Patientstaticformatrix.aspx?parentid=" + selectedRow.Cells[0].Text + "&firstname=" + selectedRow.Cells[1].Text + "&lastname=" + selectedRow.Cells[2].Text);
} else {
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
}
}
And to retrieve the values from the Request.QueryString object on the second page.
protected void Page_Load(object sender, EventArgs e) {
if (this.Page.PreviousPage != null) {
//Retrieve values from Query Strings
Response.Write("PatientId: " + Request.QueryString["parentid"].ToString() + "<br />");
Response.Write("firstname: " + Request.QueryString["firstname"].ToString() + "<br />");
Response.Write("lastname: " + Request.QueryString["lastname"].ToString() + "<br />");
}
}
Both of these solutions should meet your requirements, however they are both slightly different. The Session Variable solution is probably the preferred method as it will stop users from being able to see all of the data passed (if you need to pass confidential information) where as the Query String values will be available to anyone who can see the URL.
For more information on Session Variables and Query Strings see the below resources :
ASP.NET Session State Overview
Request.QueryString Collection
#Nunners answer is ownsome, but can also try with following way:
on anothoer page's pageload event fetch grid like:
GridView GridView1 = (GridView)this.Page.PreviousPage.FindControl("GridView1");
All the technique is given below:
http://www.aspsnippets.com/Articles/Pass-Selected-Row-of-ASPNet-GridView-control-to-another-Page.aspx
Refer above doccument.
The real answer is that you should create the same gridview on another page. This is how 99% of ASP.NET sites work since that page at some point will be writing/updating/deleting data. Or just use the same page - why redirect to show the same data?
I found some solution:
In Source aspx after grid databind:
Session["gridtoexcel"] = yourgrid;
In destination aspx
var grid = ((GridView)Session["gridtoexcel"]);
gridToExcel.Columns.Clear();
foreach (DataControlField col in grid.Columns)
gridToExcel.Columns.Add(col);
gridToExcel.DataSource = grid.DataSource;
gridToExcel.DataBind();
this way i can 'clone' exact grid to another page. if you need some css style don't forget of add them in destination page
PS: gridToExcel is your destination grid
EDITED QUESTION
I want to pass a variable, in this case 'name' containing the string bill, to a code behind method and use debug.print to see it
string name = "bill";
<asp:ImageButton runat="server" id="DeleteButton" ImageUrl="Images/delete.jpg"
CommandArgument='<%# Eval("name") %>' CommandName="ThisBtnClick" text="Delete Me" onclick="DeleteMonth" />
I've tried:
CommandArgument='<%# Eval("name") %>'
CommandArgument='<%# Bind("name") %>'
CommandArgument='<%= "name" %>
This is my print function
protected void DeleteMonth(object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
switch (btn.CommandName)
{
case "ThisBtnClick":
Debug.Print("--" + btn.CommandArgument.ToString());
break;
case "ThatBtnClick":
break;
}
}
I think i need to databind something first but honestly I have no idea. I just get a blank when i print. Has anyone dealt with this before
EDIT
What I want to do is dynamically create a table. the name variable gets pulled from a database and then creates a table based on that name. I want the last column of the table to be an X so i can delete everything in that row. I'm using an imagebutton. here's my code
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(sqlConnectionString))
{
conn.Open();
string query = "SELECT * FROM dbo.Archive";
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(query, conn);
System.Data.SqlClient.SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string name, created, 1Updated, 2Updated, 3Updated;
name = rdr.GetString(1); // name of month
if (!(rdr.IsDBNull(2))) // checks date for a null value
{ created = rdr.GetDateTime(2).ToString(); }// if not null date is turned into a string and saved in a variable
else
{ created = "---"; } // else date is given a default value
if (!(rdr.IsDBNull(3)))
{ 1Updated = rdr.GetDateTime(3).ToString(); }
else
{ 1Updated = "---"; }
if (!(rdr.IsDBNull(4)))
{ 2Updated = rdr.GetDateTime(4).ToString(); }
else
{ 2Updated = "---"; }
if (!(rdr.IsDBNull(5)))
{ 3Updated = rdr.GetDateTime(5).ToString(); }
else
{ 3Updated = "---"; }
Response.Write("<tr><td>" + name + "</td>");
Response.Write("<td>" + created + "</td>");
Response.Write("<td>" + 1Updated + "</td>");
Response.Write("<td>" + 2Updated + "</td>");
Response.Write("<td>" + 3Updated + "</td>");
Response.Write("<td><a>1</a></td>");
Response.Write("<td><a>2</a></td>");
Response.Write("<td><a>3</a></td>");
Response.Write("<td><a>Compliance Summary</a></td>");
Response.Write("<td align = 'center'>"+name);%>
<asp:ImageButton runat="server" id="DeleteButton" ImageUrl="Images/delete.jpg"
CommandArgument='<%# Eval("name") %>' CommandName="ThisBtnClick" text="Delete Me" onclick="DeleteMonth" />
<% Response.Write("</td></tr>");
}
Use like this......
<asp:ImageButton runat="server" id="DeleteButton" ImageUrl="Images/delete.jpg"
CommandArgument='<%# Eval("UserName")%>' text="Delete Me" onclick="DeleteMonth" />
protected void DeleteMonth(object sender, EventArgs e)
{
**ImageButton btn = ((ImageButton)sender).CommandArgument;**
switch (btn.ToString())
{
case "ThisBtnClick":
Debug.Print("--" + btn.CommandArgument.ToString());
break;
case "ThatBtnClick":
break;
}
}
Use CommandArgument='<%#Eval("name")%>'
instead of CommandArgument="<%Response.Write(name);%>"
EDIT
Aren't you using Data control like GridView, FormView or DataList? if not you have to use one of those in order to use Eval method. As a example of GridView you have to bind GridView datasource first.
http://msdn.microsoft.com/en-us/library/aa479353.aspx
OR
Declare public properties for your DB fields.
How can I use Eval in asp.net to read fields from a database?
The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source.
I have a GridView on my aspx page which displays a collection of objects defined by the following class
public class Item
{
public string ItemName{get; set;}
public object ItemValue{get; set;}
}
Then in my aspx markup I have something like this
<asp:GridView ID="MyTable" runat="server">
<Columns>
<asp:BoundField DataField="ItemName" />
<asp:BoundField DataField="ItemValue" />
</Columns>
</asp:GridView>
What I want to know is:
Is there a way to use conditional formatting on the ItemValue field, so that if the object is holding a string it will return the string unchanged, or if it holds a DateTime it will displays as DateTime.ToShortDateString().
Not sure if you can use a BoundField, but if you change it to a TemplateField you could use a formatting function like in this link.
ie something like
<%# FormatDataValue(DataBinder.Eval(Container.DataItem,"ItemValue")) %>
Then in your codebehind, you can add a Protected Function
Protected Function FormatDataValue(val as object) As String
'custom enter code hereformatting goes here
End Function
Or you could do something in the OnRowCreated event of the gridview, like in this link
<asp:GridView ID="ctlGridView" runat="server" OnRowCreated="OnRowCreated" />
this function is conditional formatting based on whether or not the datavalue is null/is a double
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
Object ob = drv["ItemValue"];
if (!Convert.IsDBNull(ob) )
{
double dVal = 0f;
if (Double.TryParse(ob.ToString(), out dVal))
{
if (dVal > 3f)
{
TableCell cell = e.Row.Cells[1];
cell.CssClass = "heavyrow";
cell.BackColor = System.Drawing.Color.Orange;
}
}
}
}
}
With BoundField you should modify your Item class.
If you don't want to modify your CodeBehind ther is a sort of trick you can do using a TemplateField:
<asp:GridView ID="MyTable" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ItemName" HeaderText="Name" />
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# ((Eval("ItemValue") is DateTime) ? ((DateTime)Eval("ItemValue")).ToShortDateString() : Eval("ItemValue")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
obviously you can do it for any type of object but maybe your "Text" field would become.. complicated..
by the way.. my CodeBehind for this example was just you class Item and this Page_Load():
protected void Page_Load(object sender, EventArgs e)
{
Item i1 = new Item();
i1.ItemName = "name1";
i1.ItemValue = "foo";
Item i2 = new Item();
i2.ItemName = "name2";
i2.ItemValue = DateTime.Now;
List<Item> list1 = new List<Item>();
list1.Add(i1);
list1.Add(i2);
MyTable.DataSource = list1;
MyTable.DataBind();
}
and the result was correct ;)
i decided with the Paul Rowland solution and more one thing "if (e.Item.DataItem is DataRowView)":
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
if (e.Item.DataItem is DataRowView)
{
DataRowView rowView = (DataRowView)e.Item.DataItem;
String state = rowView[PutYourColumnHere].ToString();
if (state.Equals("PutYourConditionHere"))
{
//your formating, in my case....
e.Item.CssClass = "someClass";
}
}
}
In .NET 2.0 is even easier:
Add this method to code behind: (this example formats a double value as million with 1 digit)
public string EvalAmount(string expression)
{
double? dbl = this.Eval(expression) as double?;
return dbl.HasValue ? string.Format("{0:0.0}", (dbl.Value / 1000000D)) : string.Empty;
}
In the aspx code, use this:
<asp:TemplateField ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label runat="server" Text='<%# EvalAmount("MyAmount") %>'></asp:
</ItemTemplate>
</asp:TemplateField>