set label text to total row count of gridview - asp.net

I'm using a stored procedure in a sql database as the data source for a SqlDataSourceControl on my .aspx page. I'm then using the SqlDataSourceControl as the data source for a gridview on my page. Paging is set to true on the gridview. What i would like to do is set the text of a label to the total number of rows in the gridview. I can use this code
'labelRowCount.Text = GridView2.Rows.Count & " layers found"
to return the number of results per page, but it doesn't give me the total. I've looked in several places and haven't been successful in finding a solution.

You should use the underlying datasource that the gridview is bound to (grid.DataSource). For instance if you have bound the grid to a datatable then just cast the grids datasource into the datatable and the use the rows.count property to get the total record count. Another alternative would be to get a reference to the the grids datasource object before you set it to the grid so you can get the record count directly.
So for example (assuming you are bound to a DataTable)
int count = ((DataTable)grid.DataSource).Rows.Count;
Enjoy!

Put an event handler on "selected" for the SQL DataSource. That event handler has an argument of type SqlDataSourceStatusEventArgs. In there AffectedRows is the row count of the entire data set (not just that shown on the current page). So catch that and write it out to your label:
protected void SqlDataSource_Selected(object sender,SqlDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
// do something useful, then...
e.ExceptionHandled = true;
}
else
labelRowCount.Text = String.Format("{0} layers found", e.AffectedRows);
}

GridView2.Rows saves only the rows that are visible, so when page-size is 5 you get only 5 records. As Doug suggested you have to set the labelRowCount.Text ondatabound and not on every postback, because on postback - when the datasource is not binded again - the datasource will be nothing. So a good place could be where you bind the grid to the datasource.

Related

After editing detail record, wrong record is selected in gridview

I have a GridView displaying several records. Clicking on say the third record, displays a DetailsView below where I can edit the record. If I make changes to the record and save, the GridView refreshes and resorts and now my edited record is the 5th row. However, the 3rd row is still selected and the DetailsView now displays a different record than the one I just edited.
After an update via DetailsView, how do I make sure THAT record is reselected in the GridView no matter where it may now be in the GridView sort order?
You can keep track of the ID of each row by adding the field to the DataKeyNames of the GridView. Before you refresh the grid in code-behind, you remember the ID of the selected row (assuming here that the relevant ID is a field called ClientID):
int savedClientID = (int)gvClients.DataKeys[gvClients.SelectedIndex].Values["ClientID"];
You can then look for it after binding the data and select the corresponding row:
void gvClients_DataBound(object sender, EventArgs e)
{
gvClients.SelectedIndex = -1;
foreach (GridViewRow row in gvClients.Rows)
{
int clientID = (int)gvClients.DataKeys[row.RowIndex].Values["ClientID"];
if (clientID == savedClientID)
{
gvClients.SelectedIndex = row.RowIndex;
break;
}
}
}
UPDATE
If paging is turned on in the GridView, you may have to use the method suggested in this post: GridView in ASP.Net -- Selecting the correct row

How to assign Multiple GridView for multiple UI filter selection in asp.net WF with c#

I have four DropDownList controls. Year, Country, PC, CC
Selecting a Year populates the Country along with PC and CC DropDownList. However, if I only select Country and hit the Submit Buttonthen the result should be displayed in a GridView as follows:
List of PC || Total Transaction Amount
PC1........................ 500.00
PC2........................ 600.00
But if I select a Country, PC and CC then the results are different which also need to be displayed in a GridView:
Accounts || Total Transaction Amount
ACC1........................ 100.00
ACC2........................ 200.00
Similarity between these two process is that I will have to use the last GridView when I click on one of the List of PC from the first GridView.
Question :
Would I have have to use separate GridView controls for these two different use cases and bind search results to different GridView?
I have 2 methods where one returns a Total for a PC for a selected Country and the other method returns a Total for an Account for selected Country, PC and CC, in this case can I literally do the following where I am using same GridView for different results, which is not actually working?
protected void _UIButtonSubmit_Click(object sender, EventArgs e)
{
IEnumerable<AccountTransactionViewModel> transactions = null;
IEnumerable<TransactionTotalForProfitcenterViewModel> totalProfitcenterTranAmount = null;
if ((_UIFilterDDCountry.SelectedValue) != null)
{
//transactions = ts.GetAllTransactionsByCountry(_UIFilterDDCountry.SelectedItem.Value);
totalProfitcenterTranAmount = ts.GetTotalTransactionsForProfitcenter(_UIFilterDDCountry.SelectedItem.Value);
_UITransactionGridView.DataSource = totalProfitcenterTranAmount;
}
else if ((_UIFilterDDCountry.SelectedValue) != null
&& !string.IsNullOrEmpty(_UIFilterDDProfitcenter.SelectedValue)
&& !string.IsNullOrEmpty(_UIFilterDDCostcenter.SelectedValue))
{
transactions = ts.GetAllTransactionsByYearCountryProfitcenterCostcenter(
_UIFilterDDCountry.SelectedItem.Value,
int.Parse(_UIFilterDDProfitcenter.SelectedItem.Value),
int.Parse(_UIFilterDDCostcenter.SelectedItem.Value));
_UITransactionGridView.DataSource = transactions;
}
_UITransactionGridView.DataBind();
_UITransactionGridView.PageIndex = 0;
}
Would really appreciate if anyone can just guide me (new to asp.net and c#) through to a correct direction and suggest perhaps better option, logic, idea etc.
UIFilterDDCountry.SelectedValue can it be null? Also what are the values being bound to the dropdown.
Also you need to set the country dropdown to be mandatory, remove the country dropdown value check in your method, and reverse the condition check without country dropdown check
Try using the dropdown selectedindex value rather than selected value.
You can go ahead using a single gridview, but that would have some code to be written to change the column names and so on during runtime(code behind) based on the options selected. Else simply use 2 gridview controls and set its visiblity based on the option selected.

Rowdatabound equivalent in webdatagrid of infragistics

I am looking for rowdata bound event that we have in asp.net gridview. What I am trying to achieve is this.
e.row.rowtype == datacontrolrowtype.datarow
on data bound event of webdata grid , but it is not working so how can I achieve this.
Suggestion on how get the type of row and its event would be helpful.
Ok, not 100% sure what you mean by achieving 'this' but.. WebDataGrid offers 2 versions of such events so whatever you are attempting would probably have to do with these.
As far as I get your line of code you are interested in data rows only and the following row-related events are fired only for data rows as far as I'm aware(definitely not for headers or Summary rows from my experience):
Server side: The InitializeRow event is raised when the grid binds to the records in the data source. You can find that in the general control Properties or add it at top level in the markup with <ig:WebDataGrid oninitializerow="WebDataGrid1_InitializeRow"...
Within the handler you have access to both the grid and the row and this event is fired for each data row, always:
protected void WebDataGrid1_InitializeRow(object sender, Infragistics.Web.UI.GridControls.RowEventArgs e)
{
// Use:
//e.Row.DataItem
//e.Row.DataKey
//e.Row.Index
}
Client Side Row Rendered /-ing event, that is fired only when client side binding/rendering is enabled. Event fired after / before a row is rendered to the DOM, set up by adding <ClientEvents RowRendered="test" /> where test is the name of the handler function in JavaScript:
function test(webDataGrid, evntArgs) {
//The data object with all attributes
evntArgs.get_dataItem();
//Reference to the actual TR element
evntArgs.get_rowElement();
//Returns index of the row inside of its container collection.
evntArgs.get_index();
//Returns data key of the row. It is always an array of objects even in a case of a single data key field.
evntArgs.get_dataKey();
}
I think you should be able to do what you want to do with those.

How to display the master-detail tables into two xtragrid?

I have to tables:users and messages.And create the one-many relations between these tables.And,If I display this two table in single xtragrid, it's no problem,But ,I want to display into two grid,the detail of messages doesn't display. please help me!
the key code is :
1.create the dataset of users and messages:
DataSet ds = new DataSet();
ds = SqlHelper.ExecuteDataset(fbh.ConnectionString, CommandType.Text, s);
DataTable mess = ds.Tables[0];
mess.TableName = "Messages";
DataTable user = deptmentUserMessages.Tables["Users"];
DataTable m = new DataTable("Messages");
m.Merge(mess);
deptmentUserMessages.Tables.Add(m);
deptmentUserMessages.Relations.Add("**UserMessages**", user.Columns["UserName"], m.Columns["SENDER"]);
the deptmentUserMessages is the static dataset
2.in the form.load event,I have to do:
gcMessage.DataSource = master;
gcMessageDetail.DataSource = detail;
master.DataSource = pub.DeptmentUserMessages;
master.DataMember = "Users";
detail.DataSource = master;
detail.DataMember = "**UserMessages**";
the master and detail are BindingSource.
You should handle xtargrid FocusedRowChanged event to populate detail grid.
Get the primary key field value to fetch values from child table and then set the data source of child grid. Use GetRowCellValue(Int32,String) Method
private void gridView1_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e) {
if(e.FocusedRowHandle >=0)
{
/// Get master table selected row's primary column value
/// then create a DataView from the detail table
// and set datasource of detail grid.
dvUserMessages = (Filtered row by primary column value);
master.DataSource = dvUserMessages.ToTable();
}
}
Reference:Parent - Child relationship between Two GridViews
Using only event FocusedRowChanged is not enough. When the DataSource is changed, this event doesn't fires. Because the position property doesn't changes, it remains 0. And it doesn't fires when user filters rows in master grid. So, add to this example similar event handler on ColumnFilterChanged event, and also populate child grid just after setting DataSource property of master grid.

asp.net use details view if 1 record is returned and gridview if more than one record

I'm using a details view and a sqldatasource control to populate it. Every once in a while i get an error message because more than one row is returned. How can I have the data display in a gridview instead if more than one row is returned?
Databind to both and put this in the OnDataBound event or wherever appropriate in your code. (Obviously you'll need to tweak the code for the names of your objects)
if(myDataTable.Rows.Count > 1)
{
myGridView.Visible = true;
myDetailsView.Visible = false;
}
else
{
myGridView.Visible = false;
myDetailsView.Visible = true;
}

Resources