Loop through a gridview to replace the cell value - asp.net

I want to loop through a gridview cell values and replace any value which has an asterisk like 3*,4*, ** etc to change like 3(underline), 4 underline and 8 (underline)..so basically i want to remove the asterisk and underline the inetger..Please guide me on this...thank you

You can loop trough every row and cell trough this:
foreach(DataGridViewRow gridRow in myGridview.Rows)
{
for(int i = 0; i < myGridview.Columns.Count; i++)
{
if(gridRow.Cells[i].Text.Contains('*'))
{
//Do your thing
gridRow.Cells[i].Text=gridRow.Cells[i].Text.Replace(#"*", "");
gridRow.Cells[i].Style.Font = new Font("Ariel", 8, FontStyle.Underline);
}
}
}

You can achieved this by using RowDataBound Event.. No need to loop
GridView.RowDataBound Event
The following example demonstrates how to use the RowDataBound event to modify the value of a field in the data source before it is displayed in a GridView control.
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Display the company name in italics.
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
}
}

Related

how to bind substring into gridview and

I am using a gridview to show my db table data. but there is a column called "Description " with 1000 characters. I don't want bond whole string into gridview. How I bind only first 100 characters into gridview column???
when I click select button I want make to popup window with selected column details. At this moment I want to show all characters of Description column.
I have already created popup window and other things. but still I could not get first 100 letters of "description column" and bind it into gridview. How can I do this ? And how I get whole string into popup window?
ALL ANSWERS ARE WELCOME.. PLEASE HELP ME.
THANK YOU
If you have an entity that you bind to your gridview, you can do this:
First, add a new property:
[NotMapped]
public string CutDescription
{
get
{
if (Description.Length <= 1000)
{
return Description;
}
return Description.Substring(0, 1000) + "...";
}
}
Then you can bind this to your gridview:
<asp:BoundField DataField="CutDescription" HeaderText="Description" />
This is just one way to do it. Hope it helps.
EDIT:
Another way using RowDatabound event:
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
var row = e.Row;
if (row.RowType == DataControlRowType.DataRow)
{
// Just change the index of the cell
var description = row.Cells[1].Text;
if (description.Length > 100)
{
row.Cells[1].Text = description.Substring(0, 100) + "...";
}
}
}
I fond the solution myself
100% working and fully tested
protected void grdName_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[8].Text.Length > 100)
{
e.Row.Cells[8].Text = e.Row.Cells[8].Text.Substring(0, 12);
}
}
}

How to get row count inside Gridview label

I have an ItemTemplate Label inside Gridview which I haven't bound with any DataField.
I have userId as one of the columns of GridView.
Based on the userId column, I want to get total no of assets acquired by the User. The totalNo doesn't exists in the database. I have to manually fire a query and get total no of row counts.
Now, how to put this rowCount for each user inside GridView?
Any ideas?
I have tried onRowDataBound and FindControl, but how do I get rowIndex for that particular user?
You add an event function for the DataBound on your GridView and when its render the Header you can change it like:
protected void grdView_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].Text = "Custom header";
}
}
}

Dynamically created rows disappear from Gridviews on update/delete

Situation: I have several Gridviews on one page, and each Gridview has a dynamically created row to display the totals at the bottom. In each case, the totals row is created on a RowDataBound event. The strategy that I am using is like the one provided by Mike Dugan on his Blog.
The following is the code for one of the GridViews, but the others all do something very simular.
protected void gvWorkerHours_RowDataBound(object sender, GridViewRowEventArgs e)
{
// Keep running total of hours.
if (e.Row.RowType == DataControlRowType.DataRow)
{
totalBillableHours += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Hours"));
}
if (e.Row.RowType == DataControlRowType.Footer)
{
int numColumns = gvWorkerHours.Columns.Count;
int hoursIndex = 4; //5th column, 0-based
int rowIndex = gvWorkerHours.Rows.Count + 1;
CreateTotalRow((Table)e.Row.Parent, rowIndex, totalBillableHours, hoursIndex, numColumns);
}
}
private void CreateTotalRow(Table table, int rowIndex, double totalValue, int totalIndex, int numColumns)
{
TableCell[] cells = new TableCell[numColumns];
for (int i = 0; i < numColumns; i++)
{
TableCell cell = new TableCell();
Label label = new Label();
label.Font.Bold = true;
if (i == 0)
{
label.Text = "Total";
}
else if (i == totalIndex)
{
label.Text = totalValue.ToString();
}
else
{
label.Text = "";
}
cell.Controls.Add(label);
cells[i] = cell;
}
GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
row.Cells.AddRange(cells);
table.Rows.AddAt(rowIndex, row);
}
Problem: If a user clicks on an edit/delete command for any row on any of these Gridviews, it will make the totals row disappear for all other Gridviews. As I understand, this is because a PostBack is occurring, however the RowDataBound events will not occur for the other GridViews, rather they will just reload their data from the ViewState, which does not contain the totals.
Failed attempts at solving: I cannot simply call DataBind on each of the GridView during a PostBack, because that will prevent the update/delete from occurring. Although the RowCreated event will occur for the GridViews during a PostBack, this event in not sufficient because the GridViews will not have data bound and will throw an exception when I try to calculate the total. Disabling the ViewState for these GridViews seems like a solution, however there will be a lot of data to reload each time a user clicks a command. Manually saving my data to the ViewState also seems like a solution, but there does not seem to be a simple way to have the GridViews retrieve this custom data on a PostBack.
Is there any way to actually achieve what I am trying to do with ASP.NET? It seems like a simple requirement to have a totals row at the bottom of each GridView.
Thanks in advance for any help.
What if you try creating the dynamic row using the gridView.OnPreRender event instead of the gridView.RowDataBound event. This way your data you need to calculate your dynaimic row results is available but the html has not been sent to the web browser yet. Please post some more code so we can provide more insight into fixing your issue.
As recommended, I tried putting the code to create the totals row in the PreRender event rather than the RowDataBound event. This seemed to work, except that it broke all of the commands for the GridView that it was used on. It appears that manually changing the GridView disrupts its automatic behavior.
protected void gvWorkerHours_PreRender(object sender, EventArgs e)
{
double total = 0;
int numColumns = gvWorkerHours.Columns.Count;
int hoursIndex = 4; //5th column, 0-based
int rowIndex = gvWorkerHours.Rows.Count + 1;
foreach (GridViewRow row in gvWorkerHours.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label label = (Label)row.FindControl("lblHours");
total += Convert.ToDouble(label.Text);
}
}
CreateTotalRow((Table)gvWorkerHours.Rows[0].Parent, rowIndex, total, hoursIndex, numColumns);
}
OK, the way I ended up solving this was with JQuery. If anybody else is facing a similar problem, remember that the totals must be calculated when the DOM is ready, as well as at the end of any postback. To handle the postback situation, you can just call the Javascript on the client using ScriptManager.RegisterStartupScript().
Again, I had four GridViews in my circumstance, but I'll just show the JQuery code for one of them:
$(document).ready(function () {
setTotals();
});
function setTotals() {
var totalHours = getBillableHoursTotal();
if (isNaN(totalHours)) totalHours = '...editing';
$('#spanBillableHoursTotal').html(totalHours);
//... etc.
}
function getBillableHoursTotal() {
var total = 0.0;
var rows = $('table[id*="_gvWorkerHours"] tr.RegularRows');
$(rows).each(function () {
total = total + parseFloat($(this).children('td').children('span[id*="lblHours"]').html());
});
return total;
}
And for the C# on the code behind:
protected void Page_Load(object sender, EventArgs e)
{
// ... preceeding Page Load code
if (IsPostBack)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "?", "setTotals()", true);
}
}

is there a convenient way to filter by a group column in XtraGrid GridView without displaying that column?

this is a continuation of my previous question is there off-the-shelf convenient way to filter by a group column in XtraGrid GridView? .
I was told to set GridView.OptionsView.ShowGroupedColumns to true, but that simply sucks. I don't want to waste horizontal space in my grid showing the group columns - it is sufficient to show them as group headers. I only want to have nice filter textboxes for those columns on top.
Any other suggestions short of rolling my own?
XtraGrid cannot show the auto filter editor behind the group column if the corresponding column is not shown in the column header panel. A possible solution is to show an external editor near the grid. One more solution - is to show an editor at the position of the group column header. In this case, you will have to implement filtering and managing the editor yourself. Something like this:
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Drawing;
using DevExpress.Data.Filtering;
private void gridView1_Click(object sender, EventArgs e) {
MouseEventArgs args = e as MouseEventArgs;
GridView view = sender as GridView;
GridHitInfo hitInfo = view.CalcHitInfo(args.X, args.Y);
if(hitInfo.InGroupColumn) {
ShowFilterEditor(hitInfo.Column);
}
}
private void ShowFilterEditor(GridColumn gridColumn) {
GridView gridView = gridColumn.View as GridView;
GridViewInfo vInfo = gridView.GetViewInfo() as GridViewInfo;
for(int i = 0; i < vInfo.GroupPanel.Rows.Count; i++)
for(int j = 0; j < vInfo.GroupPanel.Rows[i].ColumnsInfo.Count; j ++) {
GridColumnInfoArgs columnInfo = vInfo.GroupPanel.Rows[i].ColumnsInfo[gridColumn];
if(columnInfo != null) {
Rectangle columnRect = columnInfo.CaptionRect;
TextEdit edit = new TextEdit();
gridControl1.Controls.Add(edit);
edit.SetBounds(columnRect.Left, columnRect.Top, columnRect.Width, columnRect.Height);
edit.Focus();
edit.KeyPress += new KeyPressEventHandler(edit_KeyPress);
edit.KeyDown += new KeyEventHandler(edit_KeyDown);
edit.Disposed += new EventHandler(edit_Disposed);
edit.Tag = gridColumn;
return;
}
}
}
void edit_Disposed(object sender, EventArgs e) {
TextEdit edit = sender as TextEdit;
edit.KeyPress -= new KeyPressEventHandler(edit_KeyPress);
edit.KeyDown -= new KeyEventHandler(edit_KeyDown);
edit.Disposed -= new EventHandler(edit_Disposed);
edit.Tag = null;
}
void edit_KeyDown(object sender, KeyEventArgs e) {
if(e.KeyCode == Keys.Return)
BeginInvoke(new MethodInvoker(delegate { (sender as TextEdit).Dispose(); }));
}
void edit_KeyPress(object sender, KeyPressEventArgs e) {
BeginInvoke(new MethodInvoker(delegate {
TextEdit edit = sender as TextEdit;
if(edit.IsDisposed)
return;
GridColumn column = edit.Tag as GridColumn;
column.FilterInfo = new ColumnFilterInfo(new BinaryOperator(column.FieldName, string.Format("%{0}%", edit.Text), BinaryOperatorType.Like));
}
));
}

String manipulation in GridView on render (or prerender)

I need to dynamically modify the contents of a column in a GridView1 before it is displayed. Basically, I need to convert every 'Environment.NewLine' in a field to a so it displays as a new line on an ASP.NET page.
How do I do this?
You can use the RowCreated event to alter rows as they have been created and then edit specific columns. I think to get the columns you use
void ProductsGridView_RowCreated(Object sender, GridViewRowEventArgs e)
{
e.Row.Cells[1] += "<br />"
}
I assume you're using a data source to bind this grid. If so, I'd suggest the RowDataBound event. I doubt you'd have any newlines in your header row, but there isn't much sense in checking or appending HTML to them.
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
e.Row.Cells[i].Text.Replace(Environment.NewLine, "<br />");
}
}
}

Resources