I have one DataTable like this:
Attribute Percentage ReferenceAmount TaxAmount
------------ ------------ ---------------- -----------
Sales 5.00 5000 250
VAT 2.00 250 5
Discount 0 0 100
I want to Bind this DataTable with one GridView.
But in the GridView, I dont want to display 0. Instead of Zero, I just want leave that cell as empty. I dont want to display any other thing if that contains Zero.
How to replace EmptyString instead of Zero in the DataTable?
I am answering the question late, I know the answer is already accepted. But in the accepted answer, you are iterating the rows after databinding and then setting the value.
It would be better to replace the value at DataBinding time. It will over come the extra overhead of the iteration of the gridview rows.
You can use the RowDataBound event of the GridView. Here is the complete code..
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRow dr = ((System.Data.DataRowView)e.Row.DataItem).Row;
if (dr["Percentage"].ToString() == "0")
{
((Label)e.Row.FindControl("lblPercentage")).Text = "";
//this is template field
//OR---If you don't use template field you can do like..--
e.Row.Cells[1].Text = "";
}
}
}
The following GridView DataBound method will loop through every cell in the GridView and replace "0" with an empty string:
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
for (int i = 0; i < row.Cells.Count - 1; i++)
{
if (row.Cells[i].Text == "0")
{
row.Cells[i].Text = "";
}
}
}
}
you could easily add an property called PercentageDescription as String
public string PercentageDescription
{
return Percentage == 0 ? " " : Percentage.ToString();
}
Related
I'm trying to figure out a way in which a cell in a GridView is visible based on it's associated column in the bound DataTable. The issue I believe I'm having is that this table is dynamic and perhaps as rows are added to the table, the table is not being re-populated/re-freshed on the asp page.
Here is the scenario:
I have a table, for example, of three columns and one row. Column 1 is the index, column 2 is a name, column 3 is true or false which is meant to set the visibility of a link in the asp page.
Row 1 is already set as 1, John Doe, false so on the asp page all you see is
1 | John Doe
You can hit a drop down, click a name, and then add this name to the datatable. By default column 3 is inserted with a true value. So after the row is inserted into the table the row is reflected on the asp page as so
1 | John Doe
2 | Jane Doe
But because column 3 is true, I would like a 'delete' button to be visible so the asp page would instead look something like this
1 | John Doe
2 | Jane Doe | Delete
Where 'Delete' is a link for deleting that newly inserted row.
I've found this thinking this is exactly what I need but the 'Delete' link still fails to display in the GridView.
What am I overlooking so that I can simply display an asp:LinkButton (or any link equivalent) based on a cell value in a DataTable?
Edit
Addition of RowDataBound eventhandler function.
protected void NamesGV_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.Header) {
for (int i = 0; i < e.Row.Cells.Count; i++) {
e.Row.Cells[i].BackColor = System.Drawing.Color.Beige; ;
}
}
}
So something like this...not tested so you may need to tweak it a bit:
protected void NamesGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
e.Row.Cells[i].BackColor = System.Drawing.Color.Beige;
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Get reference to the button you want to hide/show
LinkButton delButton = CType(e.Row.Cells(2).FindControl("lbYourLinkButtonId"), LinkButton);
//check your data for value
bool visible = (bool)DoACheckForAValue(NamesGV.DataKeys(e.Row.RowIndex).Value);
delButton.Visible = visible;
}
}
I am working with a GridView that looks like an excel spreadsheet. I need to select a cell or hover over that cell and display the row and column values of that particular cell of the GridView.
My specific requirement is to hover the mouse over the gridView cells and display in a tooltip the value inside that cell, the value of its row and the value of its column.
EDIT:
The gridView represents a table that has its columns representing days and its rows representing Users. The first columns has the names of the users and the first row has the days of the month.
The following code shows the name of the user when i put my mouse over a cell. But I also need to show the day that the cell belongs to.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.ToolTip = "User: " + (e.Row.DataItem as DataRowView)["User"].ToString() + "Day: ";// Day needs show what day the cell belongs to
}
}
I hope I could explain myself correctly.
SOLUTION:
I came up with a solution that worked for me.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int days = DateTime.DaysInMonth(2015, 4);//Specific year
for (int i = 1; i < days; i++)
{
e.Row.Cells[i].ToolTip = i.ToString() + (e.Row.DataItem as DataRowView)["User"].ToString();
}
}
}
This is a short version of the code that solved my problem.
i have a problem. Here is my problem:
I got something like this in my DataGridView:
Product Code || Quantity || Description || SubTotal || Total || ....... (and so on)
SM0001 for the Product Code,
100 for the Quantity,
AS 5 for the Description,
10,000 for the Sub Total, and 1,000,000 for the Total
The above it's correct because 10,000 times 100 we get 1,000,000
I add data to the DataGridView and when the data has been added to the DataGridView, i click edit in that DataGridView, when i change some value on it, it will be changed and updated. But, the problem is when i tried to change the "Quantity" from 100 to 500, it didn't change the Total, the Total suppose to update and change too based on Quantity * Sub Total (because i change the Quantity)
How is it like that?
Here is the code for my problem above when i tried to update it from DataGridView:
private void DataGridViewCalculation(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
int _quantity = Convert.ToInt32(this.dataGridView1.Rows[i].Cells[1].Value);
int _subTotal = Convert.ToInt32(this.dataGridView1.Rows[i].Cells[3].Value);
int _total = Convert.ToInt32(_quantity * _subTotal);
this.dataGridView1.Rows[i].Cells[4].Value = _total;
}
dataGridView1.DataSource = null;
dataGridView1.DataSource = _ds.Tables[0];
}
Here is the screenshot of my problem above after and before i change the quantity to 500 from 100:
Screenshot above display when i haven't change the Quantity to 500 (still at 100)
Screenshot above display when i already changed the Quantity to 500, but the Total still the same as Quantity 100
Basically, i want when user click EDIT in DataGridView and made changes in it (let's say user make changes on Quantity in DataGridView, the Total in DataGridView should change too)
EDITED:
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(this.DataGridViewCalculation);
private void DataGridViewCalculation(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex.Equals(1))
{
int _total = Convert.ToInt32(dataGridView1["Quantity", e.RowIndex].Value) * Convert.ToInt32(dataGridView1["SubTotal", e.RowIndex].Value);
dataGridView1["Total", e.RowIndex].Value = _total.ToString();
}
}
NOTE:
The edited code still not working when i tried to change the Quantity value, the Total still remains same.
You can use CellValueChanged event. This event will be raised when cell value is changed.
Basically what you have to do is,
Check if the Quantity cell is edited by checking column index
Get the value of Sub Total column and Quantity in the same row using RowIndex of the edited cell.
Multiply both and set it to the Total cell.
Sample Code
Please note that this is a sample code, You may have to consider converting values to the required numeric format before performing any operation.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex.Equals("column Index of Quantity"))
{
double total = Convert.ToDouble(dataGridView1["Subtotal column name", e.RowIndex].Value) * Convert.ToDouble(dataGridView1["Quantity column name", e.RowIndex].Value);
dataGridView1["Total Column name", e.RowIndex].Value = total.ToString();
}
}
I have a simple gridview.
3 Columns |
NAME AGE Birthday
On RowUpdated I want to get something like:
Gridview1.Column[2].Cell[2].Text
so I can get the value from the column 2. How can I do it?
Thank you.
pS: row updated & row updating are the same thing?
Here's the MSDN article with example code: GridView.RowUpdating Event
Row updated and updating are not the same. Updating happens before the GridView control updates the row and updated is after the data has been updated.
In your Gridview control you need to add OnRowUpdating="TaskGridView_RowUpdating"
Assuming the value is in a textbox in the Age column this is how you would store the value in a string:
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = TaskGridView.Rows[e.RowIndex];
String str = ((TextBox)(row.Cells[1].Controls[0])).Text;
}
If you have data directly in the GridView cell (no label or textbox, etc) then this worked for me
protected void GridView1_RowUpdating(object sender,
System.Web.UI.WebControls.GridViewUpdateEventArgs e )
{
int row;
int colidx =1;
string cellvalue;
GridViewRow row = Gridview1.rows[e.rowindex]
cellvalue = row.cells[colidx].text;
}
Try this:
Gridview1.Rows[Gridview1.EditIndex].Cells[2].Text.ToString();
I'm new to using the C#/.NET programming Language and I have created a DataGridView for adding, editing and deleting records.
I am using Visual Studio 2010 for coding. I have put in an unbound column for row number and have this method for displaying the auto generated row numbers.
private void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells["rownumber"].Value = row.Index + 1;
}
e.Row.Cells["min_bracket"].Value = 0;
e.Row.Cells["max_bracket"].Value = 0;
e.Row.Cells["tax_percent"].Value = 0;
e.Row.Cells["add_amount"].Value = 0;
}
This does work when inserting values into the datagrid but does not show any numbers in the rownumber column when retrieving values.
How do I get to have auto generated numbers in the header instead of having to create an unbound column like I have that works when inserting rows and retrieving records?
To display text in the row header you can use the Row.HeaderCell.Value as shown below:
void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridView gridView = sender as DataGridView;
if (null != gridView)
{
foreach (DataGridViewRow r in gridView.Rows)
{
gridView.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
}
}
}
This only displays the row number of the new row when the user begins typing in it. Not sure if there is a simple way of always showing the row number on the new row.
I use a ViewState to do this, as follows:
Add a template column for the row count
Bind its content to a property like SeqNo
Create the property SeqNo in your code-behind, returning the current row count (try the below code)
int _seq = 0;
public int SeqNo {
get {
if (ViewState["seq"] == null) {
ViewState["seq"] = 1;
} else {
ViewState["seq"] = int.Parse(ViewState["seq"].ToString()) + 1;
}
_seq = int.Parse(ViewState["seq"].ToString());
return _seq;
}
}
And for the aspx side ,add the template Column to your interest GridView as the following
<asp:TemplateField HeaderText="" >
<ItemTemplate>
<%=SeqNo%>
</ItemTemplate>
</asp:TemplateField>
I thought this was a very simple solution for Windows Forms. You can customise the drawing as you wish.
Create the following class:
Public Class DataGridViewNumberedRow
Inherits DataGridViewRow
Protected Overrides Sub PaintHeader(graphics As System.Drawing.Graphics, clipBounds As System.Drawing.Rectangle, rowBounds As System.Drawing.Rectangle, rowIndex As Integer, rowState As System.Windows.Forms.DataGridViewElementStates, isFirstDisplayedRow As Boolean, isLastVisibleRow As Boolean, paintParts As System.Windows.Forms.DataGridViewPaintParts)
MyBase.PaintHeader(graphics, clipBounds, rowBounds, rowIndex, rowState, isFirstDisplayedRow, isLastVisibleRow, paintParts)
graphics.DrawString(rowIndex + 1, SystemFonts.MenuFont, Brushes.Black, rowBounds)
End Sub
End Class
Then, set the default row template for your data grid view like this:
DataGridView1.RowTemplate = New DataGridViewNumberedRow