How to get row count inside Gridview label - asp.net

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";
}
}
}

Related

Loop through a gridview to replace the cell value

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>";
}
}

Searching in the gridview + storing in the variable

I have a textbox, button and a gridview. The gridview will display the username depending on the email address written in the textbox. I want to store this username in a variable. How can i do tht? If there are many usernames in the gridview, i want to store then in an array. How can I do that too?
I got the solution
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
string Users = GridView1.Rows[i].Cells[0].Text;
}
}
U can store these details in database by writing insert statements inside for loop

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);
}
}

gridview column delete

Is there any other way to delete gridview column except using index..
I am using gridview with multiple checkbox.
I want to delete all those column whose checkboxes are checked..
I am retriving checkboxes as..
protected void ButtonApprove_Click(object sender, EventArgs e)
{
StringCollection sc = new StringCollection();
string id = string.Empty;
for (int i = 0; i < GridView1.Rows.Count; i++)//loop the GridView Rows
{
//find the CheckBox
CheckBox cb =
(CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
if (cb != null)
{
if (cb.Checked)
{
// get the id of the field to be deleted
id = GridView1.Rows[i].Cells[1].Text;
// add the id to be deleted in the StringCollection
sc.Add(id);
}
}
}
UpdateRecords(sc);
}
Please go through the Link for deleting multiple items
Check this to move the selected to another gridivew Move

How do you handle the SelectedIndex of a sortable ListView?

I have an asp.net ListView that is sortable.
I have a button with a "select" command name. When I click on the button the appropriate row gets selected. If I then click on a sort header the ListView will sort, but the selected index will stay the same. In other words if I click the 2nd row then sort the 2nd row is still selected.
Is there a way to make the ListView select the appropriate row after it sorts so that if I click an item then sort the same item will still be selected but in a different position depending on the sort?
You have to do it programmatically - although the solution is somewhat nasty.
First step is to define DataKeys and onSorting and Sorted events in ListView as below
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" DataKeyNames="AddressId,AddressLine1"
onsorting="ListView1_Sorting" onsorted="ListView1_Sorted">
Then in the code behind you have to handle the events.Since the DataItems on the Items collection is always null and DataIndex and DisplayIndex are not set as one would normally expect we have to use DataKeys.Store datakey of selected Item before sort and after sort search through DatakEy collection to match with stored datakey. See below
private DataKey dk;
protected void ListView1_Sorting(object sender, ListViewSortEventArgs e)
{
dk= (ListView1.SelectedIndex > 0) ? ListView1.DataKeys[ListView1.SelectedIndex] : null;
}
protected void ListView1_Sorted(object sender, EventArgs e)
{
if (dk == null) return;
int i;
ListView1.DataBind();
for (i = 0; i < ListView1.DataKeys.Count; i++)
if(AreEqual(ListView1.DataKeys[i].Values,dk.Values)) break;
if (i >= ListView1.DataKeys.Count) return;
ListView1.SelectedIndex =i;
}
private bool AreEqual(System.Collections.Specialized.IOrderedDictionary x, System.Collections.Specialized.IOrderedDictionary y)
{
for (int i = 0; i < x.Count; i++)
if (!x[i].Equals(y[i])) return false;
return true;
}

Resources