asp.net gridview set format for unbound field - c#

i have a gridview populated by the code below:
protected void CautaProiect_Click(object sender, EventArgs e)
{
wipDBTableAdapters.GetSummaryProiectTableAdapter proiecte = new wipDBTableAdapters.GetSummaryProiectTableAdapter();
SummaryGrid.DataSource = proiecte.GetData(CodProiect.Text);
SummaryGrid.DataBind();
}
The gridview will be populated with some columns with values.
The problem is that the values are formated like this 1234.5600 and i want them to be like 1,234.56
How ca i do this ?

You can format your data in the OnRowDatabound event
sample:
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l = (Label)e.Row.FindControl("lblValue");
l.Text = String.Format("{0:C}", l.Text);
}
}

In your GridView columns, use the DataFormatString property and set it to the format you prefer. In your case, you'll want to use "N2".
A great cheatsheet of other formatting options can be found here.

you can use the following code to display in the gridview ItemTemplate
<asp:Label ID="lblFinalPrice" runat="server" Text='<%#Convert.ToDouble(Eval("FinalPrice")).ToString("#.00")%>'></asp:Label>

I have finally managed to find an answer for this :
Here is how :
protected void SummaryGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
double value = Convert.ToDouble(e.Row.Cells[4].Text);
e.Row.Cells[4].Text = value.ToString("#,#.##");
}

Related

asp.net c# Change gridview row color after updating data [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm working on asp.net project and I am using a GridView with SqlDataSource.
I have edit enabled on the GridView, so I want the row color to be changed after admin edit and update the row. How can I do that?
You can do as following:
Create a property to record the last row you edit and remain state by ViewState:
public int LastEditRowIndex
{
get { return (int)ViewState["LastEditRowIndex"]; }
set { ViewState["LastEditRowIndex"] = value; }
}
Assign default value in case NullPointer:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LastEditRowIndex = -1;
}
}
Then record the edited row index whenever updating is done:
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
LastEditRowIndex = GridView1.EditIndex;
}
Finally, change CSS on RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex == LastEditRowIndex)
e.Row.CssClass = "bg-color-red";
}
Don't forget add the style in your Style Sheet:
.bg-color-red
{
background-color: Red;
}
In GridView's RowUpdating event try this:
GridViewRow gvrEdit = GridView1.Rows[e.RowIndex];
gvrEdit.BackColor = Color.LightPink;
So I have tried everything and nothing seems to work for me, so what I did is i added a new entity in database and i named it Edited
Then I set visibility of Edited to false in Gridview and when ever update is done it inserts 1 to Edited
And i added this code to RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
if (drv["ColumnName"].ToString().Equals("Something"))
{
e.Row.BackColor = System.Drawing.Color.Red;
}
}
I know it's probably a bad way to do it but it works
Nest an <AlternatingRowStyle> element between the opening and closing tags of your GridView.
<asp:GridView ID="GridView1" runat="server" >
<Columns>
</Columns>
<AlternatingRowStyle BackColor="DarkRed"
ForeColor="DarkBlue"
Font-Italic="true" />
</asp:GridView>
Link: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.alternatingrowstyle(v=vs.110).aspx
Put this code inside GridView's RowDataBound event edit section:
protected void Databound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
YOUR GRIDVIEWID.EditIndex == e.Row.RowIndex)
{
YOUR GRIDVIEWID.EditRowStyle.BackColor = System.Drawing.Color.YOURCOLOUR;
}
}
You can have OnRowUpdating event and handle it.
void GridView1_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
{
GridView1.Rows[e.RowIndex].Attributes.Add("style", "background-color:Red;");
}

How to replace text in some cells of GridView after data binding?

I have a GridView that is assosiated with database. Here's a data binding:
protected void GridViewProgramms_SelectedIndexChanged(object sender, EventArgs e)
{
int rowIndex = ((GridView) sender).SelectedIndex;
var programid = ((GridView) sender).Rows[rowIndex].Cells[1].Text;
GridViewEx.RowEditing += GridViewEx_RowEditing;
SqlDataSource1.SelectParameters["ID"].DefaultValue = programid;
GridViewEx.DataBind();
ExcersicePanel.Visible = true;
PanelAp.Visible = false;
}
Everything works fine, but I need to change some cells values in GridView after that. I need to rewrite every Cell in the last row. How to do this without affecting the database?
You will need to write your code(To change the cell text) in RowDataBound event of the gridview after data bind
Refer following link for more explanation
Update GridView Column after databinding
protected void GridViewEx_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
label or textbox ddltype = (label or textbox)e.Row.FindControl("id");
ddltype.text="ur text";
}
}

Null Value in Label object

I have created on GridView with Label. I have written store procedure to get StatusCode
SELECT StatusCode
From TableName
This line in GridView
< asp:Label ID="lblStatusCode" runat="server" Visible="false"
Text='<%#DataBinder.Eval(Container.DataItem, "StatusCode")%>' />
These lines in .cs file
Label lblStatusCode = (Label)row.FindControl("lblStatusCode");
objJV.Status = Convert.ToInt32(lblStatusCode.Text);
but in lblStatusCode.Text it is showing NULL even though there is value in Table.
When I execute stored procedure independently it is giving values.
// bind function
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindJVJobValidationDetails();
}
}
protected void BindJVJobValidationDetails()
{
JVSummary objJV = new JVSummary();
DataSet dataJobValidation = new DataSet();
if (SessionVariables.PERID != null)
{
dataJobValidation = objJV.GetjvTransaction(SessionVariables.PERID);
gvEmployee.DataSource = dataJobValidation;
gvEmployee.DataBind();
}
}
What might be the problem...?
The text is applied to the control on the page AFTER the code behind runs. Can't you set the text in the code behind?
Edit: You are setting the value of the label on the page i.e aspx / ascx using Container.DataItem but this value is set after the code behind has run. Basically, when the code behind looks at the control it's text property hasn't been set yet. Instead, add a DataRowBinding event to your GridView and set the lblStatusCode.Text in the event in the code behind.
Please try this code on gridview's event
OnRowDataBound="GridView_RowDataBound"
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.DataItem) != null)
{
Label lblStatusCode = (Label)e.row.FindControl("lblStatusCode");
objJV.Status = Convert.ToInt32(lblStatusCode.Text);
}
}
}

Trying to populate drop-down list in GridView edit

I have the following code trying to populate drop-down list when I click edit on a Grid View, and it gives me the following error:
" 'ddlgvRoom' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value"
Any idea on why I need to add code into the row editing event, and if so can you help? My gridview is getting its values from an objectdatasource.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
DropDownList dl = (DropDownList)e.Row.FindControl("ddlgvRoom");
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddlgvRoom = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlgvRoom");
string strgvRoom = ddlgvRoom.SelectedItem.Text.ToString();
DropDownList ddlgvJack = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlgvJack");
string strgvJack = ddlgvJack.SelectedItem.Text.ToString();
DropDownList ddlgvVlan = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlgvVlan");
string strgvVlan = ddlgvVlan.SelectedItem.Text.ToString();
GridView1.DataBind();
}
}
Had to take off the selectedvalue off the HTML side and everything started working

How to get the bound item from within an ASP.NET repeater

I have to set a LinkButton's OnClientClick attribute but I don't know what this value is until the LinkButton is bound to. I'm trying to set the value when the repeater binds, but I can't workout how to get the 'boundItem/dataContext' value...
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton Text="HelloWorld" ID="Hyper1" runat="server" OnDataBinding="Repeater1_DataBinding" >
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<TestObject>();
list.Add(new TestObject() {TestValue = "testing1"});
list.Add(new TestObject() { TestValue = "testing2" });
list.Add(new TestObject() { TestValue = "testing3" });
this.Repeater1.DataSource = list;
this.Repeater1.DataBind();
}
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
//link.DataItem ???
}
Is there anyway to find out what the current rows bound item is?
Maybe you need to use ItemDataBound event. It provides RepeaterItemEventArgs argument which has DataItem available
this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem;
}
I assume you are trying to get the value for the row that is currently being databound?
You can change your function to:
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
string valueYouWant = Eval("TestValue").ToString();
// You could then assign the HyperLink control to whatever you need
link.Target = string.Format("yourpage.aspx?id={0}", valueYouWant);
}
valueYouWant now has the value of the field TestValue for the current row that is being databound. Using the DataBinding event is the best way to do this compared to the ItemDataBound because you don't have to search for a control and localize the code specifically to a control instead of a whole template.
The MSDN library had this as a sample event handler:
public void BindData(object sender, EventArgs e)
{
Literal l = (Literal) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView) container.DataItem)[column].ToString();
}
(see http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx)
As you can see it is a simple demonstration of how to access the data item and get data from it. Adapting this to your scenario is an exercise left to the reader. :)

Categories