How to Get a Specific Column Value from a DataTable?
string countryName = "USA";
DataTable dt = new DataTable();
int id = (from DataRow dr in dt.Rows
where (string)dr["CountryName"] == countryName
select (int)dr["id"]).FirstOrDefault();
How to get a specific column value from a DataTable in c#
The table normally contains multiple rows. Use a loop and use row.Field<string>(0)
to access the value of each row.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
You can also access it via index:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
If you expect only one row, you can also use the indexer of DataRowCollection
:
string file = dt.Rows[0].Field<string>(0);
Since this fails if the table is empty, use dt.Rows.Count
to check if there is a row:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
datatable get specific column from row
for 3rd column
var cellValue = datatable.Rows[i][2];
better, if you know the column name,
var cellValue = datatable.Rows[i]["column_name"];
How to get a specific column value when using Datatables Selected_Row
input$foo_rows_selected
stores the row index of the selected rows. To get the value of a specific column for the selected row, simply subset the data frame.
output$selected_var <- renderText({
master_playeridlist[input$players_rows_selected, "id"]
})
DataTables - How do I return the value of a specific column for each row
Revised answer:
Your function for iterating over row data memDispTable.rows().every(function() {...})
looks good.
However, the structure of the data in each row can be either an array:
[ "value 1", "value2", "value3", ... ]
or an object:
{ field1: "value1", field2: "value2", field3: "value3", ... }
If you are not able to access values in the row data using an array index, such as row[0]
, then that suggests you need to access the data using field names: row.field1
.
You can double-check the structure of a row by printing the entire row to the console:
memDispTable.rows().every(function() {
var row = this.data();
console.log(row);
});
That will show you the row structure - and, if it's an object, you will also see the field names you need to use.
Whether you have row data as arrays or objects depends on how the data was provided to DataTables in the first place. Typically, it's via JSON data - so it depends on the structure of that JSON.
Revised Approach
Based on the updated info in the question, you have data which looks like the following sample (for two rows of test data):
[
{ "cdFirstName": "Tendon",
"cdId": "MTQ5",
"cdSurname": "Achilles",
"grpId": "MQ==",
"section": "Cub"
},
{ "cdFirstName": "John",
"cdId": "MTQ6",
"cdSurname": "Smith",
"grpId": "MQ==",
"section": "Cub"
}
]
This means you can access values in each row using the following:
memDispTable.rows().every(function() {
var row = this.data();
console.log(row.cdId);
});
So, you were very close in your comment this.row.cdId
- you just did not need the "this" part.
However, you also want to get the entered money amount from each row - and that requires a different approach. Because the amount is entered manually by a user into a field, that data is not directly visible to DataTables - it's part of the HTML table, but not part of the DataTables object.
We can combine the above row()
iterator with the same technique used previously to keep track of the grand total assigned amount, to get what you need.
That would be something like this:
function disperse() {
memDispTable.rows().data().each( function ( rowData, index ) {
var amtNode = memDispTable.cells(index, 5).nodes().to$()[0];
var amt = parseFloat($('input', amtNode ).val());
if (isNaN(amt)) {
amt = 0.0;
}
console.log( "ID: " + rowData.cdId + ", amount: " + amt );
} );
}
This iterates over each table row to get the cdId
value - which is in DataTables.
We also use a cells(index, 5)
function to get a specific cell (5) in the current row. And then we use the nodes()
function to help DataTables get access to the user-entered value in that specific cell.
Putting it all together, we have something like this - which should work as a stand-alone test file, if you want to try it (and then adapt to your specific code):
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.48/BigInteger.min.js"></script>
</head>
<body>
<div style="margin: 20px;">
<div id="showsum">Grand Total: $0.00</div>
<br><br>
<table id="demo" class="display dataTable cell-border" style="width:100%">
</table>
</div>
<script type="text/javascript">
var dataSet = [
{ "cdFirstName": "Tendon",
"cdId": "MTQ5",
"cdSurname": "Achilles",
"grpId": "MQ==",
"section": "Cub"
},
{ "cdFirstName": "John",
"cdId": "MTQ6",
"cdSurname": "Smith",
"grpId": "MQ==",
"section": "Cub"
}
];
var table;
function doSum() {
var sum = 0.0;
memDispTable.columns(5).nodes().to$()[0].forEach(function (item) {
var amt = parseFloat($('input', item ).val());
if (!isNaN(amt)) {
sum += amt;
}
});
sum = (Math.round((sum + Number.EPSILON) * 100) / 100).toFixed(2);
$('#showsum').text("Grand Total: $" + sum);
disperse();
}
function disperse() {
memDispTable.rows().data().each( function ( rowData, index ) {
var amtNode = memDispTable.cells(index, 5).nodes().to$()[0];
var amt = parseFloat($('input', amtNode ).val());
if (isNaN(amt)) {
amt = 0.0;
}
console.log( "ID: " + rowData.cdId + ", amount: " + amt );
} );
}
$(document).ready(function() {
memDispTable = $('#demo').DataTable( {
"data": dataSet,
"columns": [
{ title: "ID", "data": "cdId", "visible": false, "searchable": false },
{ title: "First Name", "data": "cdFirstName" },
{ title: "Surname", "data": "cdSurname" },
{ title: "Group", "data": "grpId" },
{ title: "Section", "data": "section" },
{ title: "Amount" }
],
"columnDefs": [ {
"targets": 5,
"name": "amt",
"data": function ( row, type, val, meta ) {
return '<input type="number" min="0" max="99999.99" step=".01" placeholder="0.00" onchange="doSum()">';
}
} ]
} );
disperse();
} );
</script>
</body>
</html>
This demo prints the following to the console:
ID: MTQ5, amount: 0
ID: MTQ6, amount: 0
And as the amounts are changed, the print-out shows the changes:
ID: MTQ5, amount: 1.23
ID: MTQ6, amount: 456.78
How to get specific column value from Datatables in javascript
Thankfully, I was able to solve it myself. Just a little bit of here and there was needed.
Below code does the requirement
$(document).on('click', '.contributor', function(e){
var aPos = tableAADataForContributors.fnGetPosition( $(this).closest('tr')[0]);
//if aPos returns an array in console, use first val at pos zero to get row data
var aData = tableAADataForContributors.fnGetData(aPos);
var actionColumnData = aData[aData.length-1];
$.each(actionColumnData, function(i, value){
alert(value.displayValue)
});
How to get list of one column values from DataTable?
You can use Linq to DataTable:
var ids = dt.AsEnumerable().Select(r => r.Field<int>("id")).ToList();
UPDATE: Without Linq
List<int> ids = new List<int>(dt.Rows.Count);
foreach(DataRow row in dt.Rows)
ids.Add((int)row["id"]);
Note for efficiency it's better to use row[index]
instead of row[columnName]
. First one just gets column by index from columns array. Latter gets column index from internal dictionary which maps names to indexes, and only then gets column by index.
Another thing to note is initializing list's capacity with rows count. If you will not do this, then internal array of list will be re-created and copied many times (depends on rows count).
And last thing to say - most efficient way with huge table (if possible) is filtering data on server side.
How to get a column value from data table with Linq
I have accomplished my result by making use of the following Linq statement
List<string> lstResult= (from table in dt.AsEnumerable()
where table.Field<int>("Id") == id
select table.Field<string>("status")).ToList();
string dtStatus = lstResult[0];
Related Topics
How to Compare Key/Value Dictionary With == Operator on a Ireadonlycollection<String>
Using X-Alt-Desc/Applying HTML to Calendar Invites in Outlook
Regular Expression for Valid Filename
How to Check If Multiple Values in an Array Are Equal to One String
Calculate a Checksum for a String
How to Generate Unique Number of 8 Digits
Linq to SQL Left Outer Join Using Lambda Syntax and Joining on 2 Columns (Composite Join Key)
Moq - Verify Exception Was Thrown
Model Id Property Null in ASP.NET MVC C#
How to Get a Specific Column Value from a Datatable
How to Pass Jquery Variable Value to C# MVC
Could Not Parse the Json File ,Error in Progam.Cs ASP.NET Core
Asp.Net Core 2 Web API Timeout Issue
How to Iterate Through the Following Json Using C#