how to add a counter to the rows of ag-grid? - ag-grid-react

I need to show the index of each row but not the index from data.
Index start from 1 and increases by 1,if I delete a row the last row before takes the index of the deleted row.
if I add new row it will increase the counter by 1.
I hope I have conveyed my idea well.
my code:
const columnDefs = useMemo(() => {
let index = -1;
return [
{
headerName: "index",
cellRenderer: () => {
return index++;
},
},
// { field: "id", headerName: "index" },
{
field: "title",
},
{
field: "content",
},
];
}, []);
it doesn't work as expected no errors but it starts from 2 and with each render or when adding a new row it starts from 6

Related

antd Table with switch component

Is it possible to get row information by switching the switch in ant design table?
https://codesandbox.io/s/mmvrwy2jkp
Yes, the second argument of the render function is the record.
you can do this
{
title: 'switch',
dataIndex: 'age',
key: 'age',
render: (e, record) => (< Switch onChange={() => handleSwitchChange(record)} defaultChecked={e} />)
}
This is how I dealed with the switch component on each row item when using Ant design. Maybe this could give you some hints.
Table Columns
const COLUMN =
{
title: 'Status',
key: 'status',
dataIndex: 'status',
// status is the data from api
// index is the table index which could be used to get corresponding data
render: (status, record, index) => {
const onToggle = (checked) => {
status = checked;
onActiveUser(index, status);
};
return (
<Space>
<Switch defaultChecked={status} onChange={onToggle} />
</Space>
);
},
},
const onActiveUser = (index, status) => {
axios.patch({ id: users[index].id }, { is_active: status })
.then((response) => {
console.log(response);
})
.catch(() => {
console.log('Failed!');
});
};

How do I correctly populate a JQuery datatable using array of objects?

The table is generated properly with the right number of rows and columns but the cells are empty. Source of data is an array of objects.
The code I used:
$('#myTable').DataTable( {
data:ar3,
"columns": [
{ title: "balance" },
{ title: "employeedetails" },
{ title: "position" },
{ title: "salaryamt" },
{ title: "startingdate" }
]
} );
`

Data not getting displayed in jqgrid

I am using jqgrid to display,sort and filter records. At the moment, I have go the js code working, but I think there is something wrong with my controller code, that is not populating the grid. I can see only an empty blak jqgrid with the message "No records to display". Please let me know whats going wrong.
Here is my code:
Controller:
public JsonResult GetData(string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pagesize = rows;
var custList = db.Customers.Select(
c => new
{
c.ID,
c.Company,
c.FirstName,
c.EMail,
c.Status
});
int totalCustomers = custList.Count();
var totalPages = (int)Math.Ceiling((float)totalCustomers / (float)rows);
if(sord.ToUpper() == "DESC")
{
custList = custList.OrderByDescending(s => s.FirstName);
custList = custList.Skip(pageIndex * pagesize).Take(pagesize);
}
else
{
custList = custList.OrderBy(s => s.FirstName);
custList = custList.Skip(pageIndex * pagesize).Take(pagesize);
}
var jsonData = new
{
total = totalPages,
page,
customers = totalCustomers,
rows = custList
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Solved my problem. Dint know I would get the solution so quickly. I removed all the existing code from the controller and just added this:
public JsonResult GetData()
{
var customers = db.Customers.Select(m => new { ID = m.ID, Company = m.Company, FirstName = m.FirstName, Email = m.EMail, Status = m.Status }).ToList();
return Json(customers, JsonRequestBehavior.AllowGet);
}
This is all it needs,just two lines of code, rest of the functionalities, ie paging, sorting, filtering is already provided by jqwidgets:) Hope this helps someone who was facing a similar problem as mine.
The script is as follows:
var source =
{
//localdata: GetData(),
url: '/Client/GetData',
datatype: "json",
mtype: 'POST',
datafields: [
{ name: 'ID', type: 'int' },
{ name: 'Company' },
{ name: 'FirstName' },
{ name: 'EMail' },
{ name: 'Status' }
]
};
var dataAdapter = new $.jqx.dataAdapter(source);
// initialize jqxGrid
$("#jqxgrid").jqxGrid(
{
source: dataAdapter,
sortable: true,
filterable: true,
pageable: true,
columns: [
{ text: 'Client Id', datafield: 'ID', width: 200 },
{ text: 'Company', datafield: 'Company', width: 200 },
{ text: 'Username', datafield: 'FirstName', width: 180 },
{ text: 'Email', datafield: 'EMail', width: 100 },
{ text: 'Status', datafield: 'Status', width: 140 }
]
});
});

In MVC 3, how do I refresh kendo grid in a partial view after I select a row in another partial view Kendo Grid?

I have a view with 3 partial views. The first partial view has a Kendo grid and when you select a row in the grid it populates and displays the 2nd partial view which has another kendo grid. It also populates and displays the 3rd partial view with another grid.
If I select a row in the 2nd kendo grid, i want it to insert data into the database table that the 3rd grid is using and I want it to refresh that 3rd grid with the new data.
I also have a custom button(retire) in the 3rd grid on each row that will also need to update that same grid by removing the item that was retired.
Can anyone help me set this up? Should I be using 3 partial views?
I guess you are using partial views to load each grid and it's data, that will work but you will have to refresh the entire page when a row is selected on the second grid in order to fill the third grid.
However Kendo Grid to a remote data source works well for this, you can then ignore loading the data into the grids within your partial views and use a bit of jQuery to ask the third grid to update on change event.
I find it much faster to fill grids with data via Ajax then when the page loads - but I have lots of data!
I have a grid updating for a person search which updates every time the search textbox changes
Grid defined as:-
$("#PersonSearch").kendoGrid({
columns: [
{ title: "Organisation", field: "cn", encoded: true },
{ title: "First name", field: "fn", encoded: true },
{ title: "Last name", field: "ln", encoded: true },
{ title: "Type", field: "pt", encoded: true },
{ title: "Date of birth", field: "db", encoded: true, format: "{0:dd/MM/yy}" },
{ title: "NHS number", field: "nn", encoded: true }
],
//sortable: { mode: "multiple" },
change: function () {
var selected = this.select()
data = this.dataSource.getByUid(selected.data("uid"));
if (data.url != "") {
.... do anything on a row being selected
}
else {
this.clearSelection();
}
},
filterable: false,
scrollable: { virtual: true },
sortable: true,
selectable: true,
groupable: false,
height: 480,
dataSource: {
transport: { read: { url: "../Person/PeopleRead/", type: "POST" } },
pageSize: 100,
serverPaging: true,
serverSorting: true,
sort: [
{ field: "cn", dir: "asc" },
{ field: "ln", dir: "asc" },
{ field: "fn", dir: "asc" },
],
serverFiltering: true,
serverGrouping: true,
serverAggregates: true,
type: "aspnetmvc-ajax",
filter: [],
schema: {
data: "Data", total: "Total", errors: "Errors",
model: {
id: "cID",
fields: {
db: { type: "date", defaultValue: null }
}
}
}
}
});
I trigger the Grid to fill with more data when the search box is changed :-
$('#GenericSearchString').keyup(function () {
// get a reference to the grid widget
var grid = $("#PersonSearch").data("kendoGrid");
// refreshes the grid
grid.refresh();
grid.dataSource.transport.options.read.url = "../Person/PeopleRead/" + $(this).val();
grid.dataSource.fetch();
});
On the server side in the Person controller I have a method PeopleRead :-
[HttpPost]
public ActionResult PeopleRead(String id, [DataSourceRequest]DataSourceRequest request)
{
WebCacheController Cache = ViewBag.Cache;
if (id == null) id = "";
string urlBase = Url.Content("~/");
var PeopleList = from c in db.Connections
where c.Person.Firstname.Contains(id) || c.Person.LastName.Contains(id)
select new
{
oID = c.Organisation.OrganisationID,
connID = c.ConnectionID,
cn = c.Organisation.Name,
fn = c.Person.Firstname,
pt =
(
c.Type == ModelEnums.ConnectionTypes.Customer ? "Customer" :
c.Type == ModelEnums.ConnectionTypes.Owner ? "Owner" :
c.Type == ModelEnums.ConnectionTypes.Service_User ? "Service user" :
c.Type == ModelEnums.ConnectionTypes.Worker ? "Worker" :
c.Type == ModelEnums.ConnectionTypes.Profile ? "Profile" : "Unknown"
),
url =
(
c.Type == ModelEnums.ConnectionTypes.Customer ? "" :
c.Type == ModelEnums.ConnectionTypes.Owner ? "" :
c.Type == ModelEnums.ConnectionTypes.Service_User ? urlBase + "ServiceUser/Details/" :
c.Type == ModelEnums.ConnectionTypes.Worker ? urlBase + "Worker/Details/" :
c.Type == ModelEnums.ConnectionTypes.Profile ? "" : ""
),
ln = c.Person.LastName,
nn = c.Person.NHSNumber,
db = c.Person.DateOfBirth
};
DataSourceResult result = PeopleList.ToDataSourceResult(request);
return Json(result);
}
Sorry the example is a bit off topic, but I though better to have working code as an example.
In your case the change: of the second grid would change the grid3.dataSource.transport.options.read.url and then do a grid3.dataSource.fetch();
I have to include the reference kendo.mvc along with many more on the mvc project as well as a link to kendo.aspnetmvc.min.js in the cshtml.

Export data from jqxgrid

I want to export all data in my jqxgrid into json and send it to another page via AJAX.
My problem is when I click export button, the data in the grid and data before export was not the same. It change float number to Interger. Here is my code:
Javascript:
$('#export_bt').on('click', function(){
var row = $("#jqxgrid").jqxGrid('exportdata', 'json');
$('#debug').html(row);
console.log(row);
});
var tableDatas = [
{"timestamp":"06:00:00","A":99.49,"B":337.77,"C":155.98},
{"timestamp":"07:00:00","A":455.67,"B":474.1,"C":751.68},
{"timestamp":"08:00:00","A":1071.02,"B":598.14,"C":890.47}
];
var tableDatafields = [
{"name":"timestamp","type":"string"},
{"name":"A","type":"number"},
{"name":"B","type":"number"},
{"name":"C","type":"number"}
];
var tableColumns = [
{"text":"Times","datafield":"timestamp","editable":"false","align":"center","cellsalign":"center","width":150},
{"text":"A","datafield":"A","editable":"false","align":"center"},
{"text":"B","datafield":"B","editable":"false","align":"center"},
{"text":"C","datafield":"C","editable":"false","align":"center"}
];
function setTableData(table_data,table_column,table_datafields)
{
sourceTable.localdata = table_data;
sourceTable.datafields = table_datafields;
dataAdapterTable = new $.jqx.dataAdapter(sourceTable);
$("#jqxgrid").jqxGrid({columns:table_column});
$("#jqxgrid").jqxGrid('updatebounddata');
$('#jqxgrid').jqxGrid('sortby', 'timestamp', 'asc');
$("#jqxgrid").jqxGrid('autoresizecolumns');
for(var i=0;i<table_column.length;i++){
$('#jqxgrid').jqxGrid('setcolumnproperty',table_column[i].datafield,'cellsrenderer',cellsrenderer);
}
}
var cellsrenderer = function (row, columnfield, value, defaulthtml, columnproperties) {
if (value||value===0) {
return value;
}
else {
return '-';
}
};
var sourceTable ={ localdata: '', datatype: 'array'};
var dataAdapterTable = new $.jqx.dataAdapter(sourceTable);
dataAdapterTable.dataBind();
$("#jqxgrid").jqxGrid({
width: '500',
autoheight:true,
source: dataAdapterTable,
sortable: true,
columnsresize: false,
selectionmode: 'none',
columns: [{ text: '', datafield: 'timestamp', width:'100%' , editable: false, align:'center'}]
});
setTableData(tableDatas,tableColumns,tableDatafields);
Html:
<div id="jqxgrid"></div>
<button id="export_bt">Export</button>
<div id="debug"></div>
http://jsfiddle.net/jedipalm/jHE7k/1/
You can add the data type in your source object as below.
datafields: [{ "name": "timestamp", "type": "number" }]
And also I suggest you to apply cellsformat in your column definition.
{ text: 'timestamp', datafield: 'timestamp', cellsalign: 'right', cellsformat: 'd' }
The possible formats can be seen here.
Hope that helps
You can export data in very fast way just like it is id jqxGrid with
var rows = $("#jqxGrid").jqxGrid("getrows");
It will be json array.

Resources