How to loop an entire GridView having AllowPaging attribute set to true? - c#

I have a GridView asp server control in a page and I have set its AllowPaging to true. Now, I want to loop to the entire rows but it only iterates to the number of PageSize that I have defined.
Here is the asp code:
<asp:GridView ID="gvName" runat="server" AllowPaging="True" PageSize="5" AutoGenerateColumns="True"></asp:GridView>
Here is the code behind:
List<string> list = new List<String>();
for(int x = 0; x <= 9; x++)
{
list.Add("Name " + (x + 1).ToString());
}
gvName.DataSource = list;
gvName.DataBind();
foreach(GridViewRow row in gvName.Rows)
{
// gvName.Rows.Count only returns 5 instead of the total number of its record that is 10
}
Thanks in advance for any kind of answer.

That's a feature, not a bug, of how the paging works-- it only loads x rows for each page load. Depending on what you need to accomplish, you could either:
Cycle through the rows on every page load (since you should only care about the visible ones anyway, right?)
Cycle through the actual data source, either using your list object, or GridView.DataSource (casting to the appropriate type first).

Use the grid event OnRowDataBound event to do all the work you want with the rows
to get the count use:
int count = list.Count;

Related

FindControl and Get Selected Value of Dropdown

This scenario is occurring when using C# code behind to find HTML Controls added dynamically from SQL Data Results.
Using the following there is an iteration though the Table rows and row each table row, we write the Controls value, in this case a HtmlSelect. The Html Select Element is in Cell 3
for (int i = 1; i <= Table1.Rows.Count - 1; i++)
{
HtmlSelect select = Form.FindControl("MainContent_selectBoxstatus" + i) as HtmlSelect;
System.Diagnostics.Debug.Write(select.Value);
}
Resulting in:
A first chance exception of type 'System.NullReferenceException'
occurred in project.dll
If i use the following:
for (int i = 1; i <= Table1.Rows.Count - 1; i++)
System.Diagnostics.Debug.Write(Table1.Rows[i].Cells[0].Text);
I get the desired result, of the text from Cell 1.
How the Select Dropdown is created:
for (int i = 0; i < dr.FieldCount; i++)
HtmlSelect sStatus = new HtmlSelect();
sStatus.Items.Add(new ListItem("Working", "0"));
sStatus.Items.Add(new ListItem("Fault", "1"));
sStatus.SelectedIndex = 0;
sStatus.Attributes.Add("class", "dropdownlist");
sStatus.ID = "selectBoxstatus" + rowindex;
cell.Controls.Add(sStatus);
That's what usually happens when you are trying to "hack" ASP.NET internals. I mean "hack" because using magic strings to resolve the auto-generated ids assigned to child controls is extremely unsafe. There are much better and safer ways to do this.
1- If you want to render a tabular layout, I'd strongly recommend using a databound control such as a GridView, ListView, etc where you can intersect its RowDatabound event and retrieve the child controls in a safe manner
2- If you can't afford to do a re-write then replace your code as follows...
for (int i = 0; i < Table1.Rows.Count; i++)
{
HtmlSelect select = Table1.Rows[i].Cells[0].FindControl(string.Format("selectBoxstatus{0}", i)) as HtmlSelect;
if(select != null)
System.Diagnostics.Debug.Write(select.Value);
}
Option 2 Code Analysis
for (int i = 0; i < Table1.Rows.Count; i++)
Nitpicking, but initializing i to 0 this makes it easier to read...believe it
HtmlSelect select = Table1.Rows[i].Cells[0].FindControl(string.Format("selectBoxstatus{0}", i)) as HtmlSelect;
I'm not too sure what Form meant in your original post but it makes more sense to use the object you're iterating....Table1 rows collection. I also refer to Cell[0] which is the first cell in the iteration's current row(feel free to adjust it)...this is still not safe but it's the only way to achieve it in the current scenario, if you need more code safety, then resort to option one. Also notice that FindControl doesn't mess around with auto-generated id, it simply uses the actual Id specified for the child control
if(select != null)
After you attempt to retrieve the select control make sure to check whether the control was successfully retrieved or not.
Hope it makes sense
Try changing your loop so that you call findcontrol on the row instead:
for (int i = 1; i <= Table1.Rows.Count - 1; i++)
{
HtmlSelect select = Table1.Rows[i].FindControl("MainContent_selectBoxstatus" + i) as HtmlSelect;
}

How to remove row from datagrid in asp.net

I have a datagrid dgCompanies declare like this:
// bind the data to the datagrid
dgCompanies.PageSize = pageSize;
dgCompanies.DataSource = rdr;
Then I need to check the records inside this datagrid:
int j = 0;
foreach (DataGridItem item in dgCompanies.Items)
{
HtmlGenericControl name = (HtmlGenericControl)item.Cells[j].FindControl("SpanTitle");
string drstring = name.InnerHtml.Trim();
if (checkingfunction(drstring))
{
//do removing record from datagrid.
I tried this: item.Cells.Remove(item.Cells[j]); but the result still there, don't see anything removed!
}
j = j + 1;
}
dgCompanies.DataBind();
How could I remove that record from datagrid dgCompanies when if condition is satisfy ?
I agree with #Andrei, it would be best to just not return that data. Otherwise you're returning and churning through data that is unnecessary. However, if in the context of you can't filter the data up front, I suppose you could add a css class "donotshow" to your rows (see How do I specify CSS classes for specific rows in a GridView?).
Then using jquery use
$('.donotshow').hide();
Again, in this regard, you are still returning all that HTML to the browser, so that will make your page size larger than necessary. Additionally, using this method could screw up pagination if you using it (example, if it says "rows 1-10", but 5 rows are hidden, then that will look goofy).
Hope this helps

sum values which are loaded in gridview

How can I plus all values of one selected row of a gridview in C# asp.net application?
For example I have a gridview in which is only one row. Values of this row are only number. So I want to plus this numbers.
I tried this loop but it writes all gridview numbers(it isn't summing them).
for (int i = 2; i < GridView1.Columns.Count; i++)
{
int x = 0;
x += int.Parse(GridView1.Rows[0].Cells[i].Text);
Response.Write(x.ToString());
}
I think you should approach this from a different perspective. The GridView is just a display control and doesn't 'hold' the data it is displaying. You are trying to use data that it really doesn't contain using a 'screen scrape' approach. You should be looking to the DataSource you bound to the grid in the first place and using the data there.
For example:
List<YourObjectWithTheNumbers> lst = something;
yourGridView.DataSource = lst;
ViewState["YourData"] = lst; // you could use Session instead: Session["YourData"]
So at this point your data is bound and saved for later use so now just update your numbers and rebind to the GridView again:
List<YourObjectWithTheNumbers> lst =
(List<YourObjectWithTheNumbers>)(ViewState["YourData"]);
int rowTotal = 0;
rowTotal += lst[0].Field1;
rowTotal += lst[0].Field2;
//etc...
yourLiteral.Text = rowTotal.ToString();
At this point you are using the actual data, not pulling it out of the grid that should be used for display purposes. It's also more secure in that you can keep the data source securely stored on the server if necessary (don't use ViewState if this is a concern) so that it can't be manipulated.
In HTML GridView render as table , better you can use Jquery to add the values ,
var total=0;
$('#gridview1').find('tr td').each(function(i, td){
var data= parseInt( $(td).val());
total+=data;
});
I created method in which I had loop and it worked !!!!!!!
public int Sum()
{
int z = 0;
int i;
int x = 0;
for (i = 0; i < GridView1.Columns.Count; i++)
{
x += int.Parse(GridView1.Rows[0].Cells[i].Text);
}
return x;
}
It was #N4TKD idea. Thanks to you !!!!

asp.net: How to manually (c#) select radiobutton in radiobuttonlist inside gridview from Session

Im having problems after postback in asp.net / c#. All radiobuttlists in gridview are cleared on postback (one radiobuttonlist on each row). So I save them to a Session variable.
But I cant set them back from the Session variable. Here is the code in page_load:
//.. testing for null,etc
for (int i = 0; i < lstRadioButtons.Count; i++)
{
RadioButtonList rbl = (RadioButtonList)gwTract.Rows[i].FindControl("RadioButtonList1");
rbl.SelectedItem.Value = lstRadioButtons[i]; //list with strings "0", etc
Debug.WriteLine("yep...");
}
Thanks in advance!
Assuming lstRadioButtons contains the value for a given row:
for (int itemIndex = 0; itemIndex < rbl.Items.Count; itemIndex++)
if (rbl.Items[i].Value == lstRadioButtons[i])
rbl.SelectedIndex = itemIndex;
Assuming lstRadioButtons contains the index for a given row:
rbl.SelectedIndex = int.Parse(i); //You may want to use TryParse to handle failure

Full text search on a bound DataGridView control

I cannot seem to be able to find a way to do a full text search on a databound DataGridView control across the entire breath of its columns and rows.
The DataTable and DataView objects seems to force me into searching for specific columns either through Select(), Find(), or FindRows(). Same with the DataGridView control.
I have one search string and I need to run it against the whole contents of the DataGridView. I'm sure the answer lies somewhere close. But I cannot seem to be able to find it at this stage in my apprenticeship of C# and the .Net framework.
This is my current solution which I would like to avoid:
/*...*/
for (int i = found_last_row + 1; i < dataGridRes.Rows.Count; ++i)
{
for (int j = 0; j < dataGridRes.Columns.Count; j++)
{
if(dataGridRes.Rows[i].Cells[j].Value.ToString().Contains(search_last_str.))
{
dataGridRes.Rows[i].Selected = true;
dataGridRes.FirstDisplayedScrollingRowIndex = i;
found_last_row = i;
break;
}
}
}
/* ...*/
I think the common approach is to search the source data (not the grid), then re-bind to only show the matches. If you use paging, the grid pulls the data page by page from the database, so you would only be searching the page that you currently see.

Categories

Resources