i have a gridview, the column has 20 records whose values are in decimal.say like 5686252.345656 i want to trim those value. So that i could see 5686252.34. It would be great if i trim it in the c# code rather in SQL.
Ive binded the values like this..
<asp:TemplateField HeaderText="Weighted Avg" SortExpression="WT_AVG"
ItemStyle-HorizontalAlign="Center" HeaderStyle-VerticalAlign="Top" HeaderStyle-Width="70px">
<ItemTemplate>
<asp:Label ID="lblWT" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"WT_AVG") %>' />
</ItemTemplate>
</asp:TemplateField>
Please help me.
Thanks.
You can apply a format string to the binding statement:
Example:
<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}") %>
I would use Math.Round(decimal d,int decimals) for example
Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.
Math.Round(4.34, 1); // Returns 4.3
Math.Round(4.35, 1); // Returns 4.4
Math.Round(4.36, 1); // Returns 4.4
http://msdn.microsoft.com/en-us/library/zy06z30k(v=vs.100).aspx
EDIT: OR do it in the SQL:
SELECT ROUND(123.9994,3), ROUND(123.9995,3)
returns: 123.9990 124.0000
Rounding on MSDN
Related
I have a GridView with two columns and I want to add a third column which will be column A divided by column B. I added a template field but I am getting a divide by zero error. How can I check for zero values to stop the error message?
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCalc" runat="server" >
<%# Convert.ToDecimal(Eval("val1").ToString()) / Convert.ToDecimal(Eval("val2").ToString()) %>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Yes, you sure can. You can even do that inline, but that would clutter your markup too much, so I would suggest moving this code to code behind.
protected decimal Calculate(string a, string b)
{
decimal ad = Convert.ToDecimal(a);
decimal bd = Convert.ToDecimal(bd);
if (bd == 0)
{
return 0; // or whatever
}
return ad / bd;
}
To call this:
<asp:Label ID="lblCalc" runat="server" >
<%# Calculate(Eval("val1").ToString(), Eval("val2").ToString()) %>
</Label>
I want to obtain the new value of a cell in the gridview rowUpdating event:
roles.RoleName = gvRoles.Rows[e.RowIndex].Cells[GetColumnIndexByName(row, "RoleName")].Text;
But the value is empty.
I have checked e.NewValues which is an ordered Dictionary. It contains the new changed value. How do I retrieve the new values for update?
aspx design is:
<asp:GridView ID="gvRoles" DataKeyNames="RoleId" runat="server"
AutoGenerateColumns="False" GridLines="Vertical" CssClass="table
table-striped table-bordered" AutoGenerateEditButton="True"
OnRowCancelingEdit="gvRoles_RowCancelingEdit" OnRowUpdating="gvRoles_RowUpdating"
OnRowEditing="gvRoles_RowEditing">
<Columns>
<asp:BoundField DataField="RoleId" HeaderText="RoleId" ReadOnly="True" />
<asp:BoundField DataField="RoleName" HeaderText="RoleName" ReadOnly="false" />
<asp:BoundField DataField="Role_Description" HeaderText="Role Description" ReadOnly="false" />
<asp:TemplateField HeaderText="RoleStatus">
<EditItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" SelectedValue='<%# Bind("Role_Status") %>' >
<asp:ListItem>True</asp:ListItem>
<asp:ListItem>False</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblRoleStatus" runat="server"
Text='<%# Bind("Role_Status") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The easiest way which i found out is to discovered e.NewValues. As I mentioned above it is an ordered dictionary and only i need to manage it.
I need to retrieve new values from this dictionary, which is done i this way.
if (!string.IsNullOrEmpty(e.NewValues["RoleName"].ToString()))
{
roles.RoleName = e.NewValues["RoleName"].ToString();
}
if you have template field it also work for it;
if (!string.IsNullOrEmpty(e.NewValues["Role_Status"].ToString()))
{
roles.Role_Status = Convert.ToBoolean(e.NewValues["Role_Status"].ToString());
}
This is the easiest thing I ever discovered. before that i want just using Find control and casting and then retrieving all lot code.
There is also e.OldValues ordered dictionary. Every one can use it to compare the new value with old ones. If values are same they could notify user to change the value(give new cell value).
GridViewRow row = (GridViewRow)gvRoles.Rows[e.RowIndex];
TextBox textRName = (TextBox)row.Cells[1].Controls[0];
string rname=textRname.Text;
Try This:
protected void gvRoles_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvRoles.Rows[e.RowIndex];
TextBox txtBox= (TextBox)(row.Cells[1].Controls[0]);
if(txtBox!=null)
{
String str = txtBox.Text;
}
}
After searching long and hard I found a great article that solved my issue. Take a look at the page load if you are binding on post back then the values get updated before you are able to access them.
Follow this link for more details --> https://taditdash.wordpress.com/2014/06/30/why-gridview-rowupdating-event-is-not-giving-the-updated-values/
The return data type ICollection is a bit tricky. Would have preferred a different data type than a string array but this was simplest direct conversion.
// grabs column headers
String[] keyStrings = new string[e.NewValues.Count];
System.Collections.ICollection keys = e.NewValues.Keys;
keys.CopyTo(keyStrings, 0);
// grabs edit row values
String[] valuesStrings = new string[e.NewValues.Count];
System.Collections.ICollection values = e.NewValues.Values;
values.CopyTo(valuesStrings, 0);
The end result here has two string arrays values and keys which can then be indexed, where the column header has the same index value as the cell value of the edited row.
I have a gridview column like this:
<asp:TemplateField HeaderText="<%$ Resources:UserProfile, C_Updated %>" ItemStyle-Wrap="false" SortExpression="Updated">
<ItemTemplate>
<asp:Literal ID="UpdatedLiteral" runat="server"
Text='<%# (Eval("Updated").ToString()) == "0" ? string.Format("<span class=greenText>{0}</span>", GetGlobalResourceObject("Vacancies", "VacancyToday")) : ((int)Eval("Updated")) %>' />
<asp:Literal ID="UpdateddaysLiteral" runat="server" Text='<%$ Resources:UserProfile, C_UpdatedDays %>' />
</ItemTemplate>
</asp:TemplateField>
value in updated field is number 0 or greater than 0. but I am getting the error:
CS0173: Type of conditional expression cannot be determined because
there is no implicit conversion between 'string' and 'int'.
Also, I want to show UpdateddaysLiteral only if updated column has value greater than 0. Please suggest how to do this ?
There should be exactly one implicit conversion between b & c in:
var value = a?b:c
This conversion can be in any direction.
What this means is that either b should be implicitly convertible to c or the reverse.
In your case you have b as String and c as Int and there is NO implicit conversion between the two. That's why this error shows up. MSDN may help.
For example, This will also show the same error:
lbldate.Text= (DateTime.Parse(TextBoxActualEndDate.Text)) : null;
So the correction is :( Making any one side convertible to other)
lbldate.Text= (DateTime?)(DateTime.Parse(TextBoxActualEndDate.Text)) : null;
In the last part of your condition:
: ((int)Eval("Updated"))
Why are you casting "Updated" back to int? Just Eval("Updated").ToString() should suffice.
Second part of your question:
<asp:Literal ID="UpdateddaysLiteral" runat="server" Visible='<%# Eval("Updated") > 0 ? "true", "false" %>' ...
Workaround: KISS Principle, that means Keep It Simple Silly.
Why are you making things complicated in your aspx, when you can do it from code behind flawlessly.
Create a method to do your comparison logic on your codebehind. Something like this.
/// This might not be you exact logic, but it will help you
public string comparevalues(string value)
{
if(Convert.ToInt32(value)>0)
{
//do something
}
else
{
// do something else;
}
return result_as_string;
}
In your aspx:
<asp:Literal ID="UpdatedLiteral" runat="server"
Text='<%#comparevalues(Eval("Value_To_Evaluate").ToString() %>' />
I am trying to find a DropDownList control on the EditItemTemplate of a grid view, to populate it with results from a query before it is drawn, but the control is never found.
ddlParent == null
Always!
I may be missing something very obvious but i have tried about 8 different methods to get this find control working, but no matter what i do, it comes up null.
I have included both the ASP and the C#, the sql should not be important as i cant even reach the call!
ASP:
<asp:TemplateField SortExpression="LocationArea2.Name" HeaderText="Parent Location Area">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("LocationArea2.Name") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlParent" runat="server" AppendDataBoundItems="true" DataTextField="LocationArea2.Name"
DataValueField="ParentID" AutoPostBack="false" SelectedValue='<%# Bind("ParentID") %>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
C#:
protected void gvLocationArea_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (gvLocationArea.EditIndex == e.Row.RowIndex)
{
DropDownList ddlParent = (DropDownList)gvLocationArea.Rows[gvLocationArea.EditIndex].FindControl("ddlParent");
if (ddlParent != null)
{
using (SalesSQLEntities db = new SalesSQLEntities())
{
ddlParent.DataSource = db.GetRecursiveAreaList(Convert.ToInt32(((TextBox)gvLocationArea.Rows[gvLocationArea.EditIndex].FindControl("txtLocationAreaID")).Text), true);
ddlParent.DataBind();
ddlParent.Items.Add(new ListItem("* None", ""));
}
}
}
}
I know there is something missing here, the control is just never found no matter what i've tried!
Instead of doing a FindControl, use an offset index of the column in question and get the first control:
(DropDownList)gvLocationArea.Rows[gvLocationArea.EditIndex].Cells[INDEX OF THE DDL].Controls[0]
I have a Grid View . It has two bound columns. I need to have a Serial Number column as the first column.
How can i do that ?
Thanks in Advance
<asp:TemplateField HeaderText="S No">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
<ItemStyle Width="2%" />
</asp:TemplateField>
Create a datatable with two columns use a first column as autoincrement as true and AutoIncrementStep=1 like
DataTable _test = new DataTable();
DataColumn c = new DataColumn("sno", typeof(int));
c.AutoIncrement = true;
c.AutoIncrementSeed = 1;
c.AutoIncrementStep = 1;
_test.Columns.Add(c);
_test.Columns.Add("description");
gvlisting.DataSource = _test;
This is more of an adjunct answer to the OP's original question. I had a terrible time figuring out how to get the index number (serial number in the OP) of the row created by the R.Ilayaraja's answer (which worked great BTW).
In your code behind page if you want to get the index number of the row, you can use code similar to this:
Int32 idNumber = Convert.ToInt32(gvlisting.Rows[i].DataItemIndex.ToString()) + 1;
This assumes you were using an iterator 'i' to get other values from your rows, and you need to add one to the number since the index is ordinal (index 0 is the first row). If you're not using an iterator, just use .Rows[0]
I struggled mightily as an ASP.NET nugget to figure this out, so I figured I'd post this in hopes it helps some other noob like me.
Add a column called Ser and set it to ReadOnly=false.
Then add this code to your application:
if (GridSearch.Rows.Count > 1)
{
for (int i = 0; i < GridSearch.Rows.Count-1; i++)
{
GridSearch.Rows[i].Cells[0].Value = (i + 1).ToString();
}
}
Just add this code in gridview
<asp:TemplateField HeaderText="Serial No of Users">
<ItemTemplate>
<%# ((GridViewRow)Container).RowIndex + 1%>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotalall" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SR No">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
<ItemStyle Width="5%" />
</asp:TemplateField>
use Row index a bound field or on row data bound you can add a template column on which you could use the index of the row.