w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
how to convert datatable to json in C#
This code snippet from Convert Datatable to JSON String in C#, VB.NET might help you. It uses System.Web.Script.Serialization.JavaScriptSerializer to serialize the contents to JSON format: public string ConvertDataTabletoString() { DataTable dt = new DataTable(); using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=master;Integrated Security=true")) { using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,description from LocationDetails", con)) { con.Open(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

Categories : Asp Net

How can I convert json string to google.visualization.DataTable?
You can use the function arrayToDataTable var jsonString = ".........."; // json string of array var array = JSON.parse(jsonString); var dataTableData = google.visualization.arrayToDataTable(array); // use dataTableData to build dataTable

Categories : Javascript

changing d3.JSON in Hierarchical Bars to JSON.parse
You're probably going to have to read a little more documentation before having a working understanding of what's going in this function. This is a tricky example to start with; I'm just going to walk you through what my process of trying to understand would look like. Going line by line: d3.json("readme.json", function(root) { This loads the referenced json file and calls function with it. 'root' starts out equal to the json file. hierarchy.nodes(root); Looking through the code, we find where hierarchy is declared: var hierarchy = d3.layout.partition() .value(function(d) { return d.size; }); So hierarchy is some kind of layout and hierarchy.nodes will add some useful attributes to root that will make it easier to graph. x.domain([0, root.value]).nice(); searching for

Categories : D3 Js

.NET Convert the contents of a DataTable to another DataTable with a different schema
I would normally do in select that "looks like" the destination table, but with data from the source table. You would apply the data conversions also as required. Select Cast (LocationNameLocationName As varChar(...) As LocName , LocX As XCoord , ... From SourceTable Hard to describe in a simple answer. what I've done in the past is issue an "empty" query like "Select * From sourcetable Where 1=0" which returns no rows but makes all the columns and their types available in the result set. You can cycle through the column ADO objects to get the type of each. You can then use that info to dynamically build a real SQL statement with the conversions. You still have a lot of logic to decide the conversion, but they all happen as you're building the statement, not as the table is being r

Categories : SQL

select column from datatable and convert this to datatable again
This will create a new table, insert the single column, and populate with rows containing original data: DataTable dt = new DataTable(); DataColumn column = new DataColumn() { ColumnName = defindedDataTable.Columns[0].ColumnName, DataType = defindedDataTable.Columns[0].DataType, Expression = defindedDataTable.Columns[0].Expression, ColumnMapping = defindedDataTable.Columns[0].ColumnMapping }; dt.Columns.Add(column); foreach (DataRow row in defindedDataTable.Rows) { DataRow newRow = dt.NewRow(); newRow[defindedDataTable.Columns[0].ColumnName] = row[defindedDataTable.Columns[0].ColumnName]; dt.Rows.Add(newRow); }

Categories : C#

Hierarchical XML to JSON
Here a small stylesheed to give you are idea how to do deal with this probelm: <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' > <xsl:output method='text' encoding="UTF-8"/> <xsl:template match="/"> { <xsl:apply-templates select="//Data[Attribute/@name ='Parent' and Attribute = '' ]/parent::Node" /> } </xsl:template> <xsl:template match="Node" > <xsl:param name="level" select="1" /> children:[ { "title": "<xsl:value-of select="Data/Attribute[@name = 'ID']" />", "level": "<xsl:value-of select="$level"/>, <xsl:apply-templates select="ancestor::Node[1]"> <xsl:with-param name="level" select

Categories : Xml

Hierarchical data.frame to JSON with irregular nodes
You need to convert the data.frame to a ragged list before calling toJSON. Try the following library(toJSON) library(data.table) # Convert the data.frame to data.table for ease of handling DT <- data.table(D) # assuming `D` is your original data.frame rList <- list() parent <- list() child <- list() grandchild <- list() j <- 1 while (j < nrow(DT)) { lastj <- j while (DT[j, parent=="" && grandparent != ""]) { rList[[length(rList)+1]] <- as.list(DT[j, list(name=grandparent, age)]) j <- j+1 } while (DT[j, child==""] && DT[(j-1):j, identical(grandparent[[1]], grandparent[[2]])] && (j < nrow(DT)) ) { parent[[length(parent)+1]] <- as.list(DT[j, list(name=parent, age)]) j <- j+1 } while(DT[j, gran

Categories : Json

recursively build hierarchical JSON tree in python
Try follwing code: import json links = (("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Tom","Hurbert"),("Tom","Neil"),("Bob","Leroy"),("Bob","Earl"),("Tom","Reginald")) name_to_node = {} root = {'name': 'Root', 'children': []} for parent, child in links: parent_node = name_to_node.get(parent) if not parent_node: name_to_node[parent] = parent_node = {'name': parent} root['children'].append(parent_node) name_to_node[child] = child_node = {'name': child} parent_node.setdefault('children', []).append(child_node) print json.dumps(root, indent=4)

Categories : Python

Mapping hierarchical JSON to TypeScript-KnockoutJS typed Object
OK, so I'm a little further down the line now, after lots of hair pulling and numerious tests. Below is a almost working example of what I'm trying to achive, the only problem with this is it doesn't seem to map correctly, even though stepping through the code seems to suggest it is loading correctly. Only when I use it with my bindings it throws a null unreferenced binding on RootTaget.Filter.Type, which should have be populated with a value. I'm still trying to figure out why, but I will welcome suggestions as to what possible wrong. :) NOW FIXED AND WORKING semi-working typescript ///<reference path="Scripts/typings/jquery/jquery.d.ts"/> ///<reference path="Scripts/typings/knockout/knockout.d.ts"/> ///<reference path="Scripts/typings/knockout.mapping/knockout.mapping

Categories : Typescript

Using JSON.net to Serialize a datatable, how do I stop it from escaping a JSON string in one of the columns
You'll need to write a custom converter to convert that DataTable to a JSON string. You can only tell JsonConvert how to convert types so you'll need to provide a converter for DataTable. A DataTable is serialized as an array of objects with a property corresponding to each of the values in a row. You'll want to deserialize the JSON_Column column first so it is treated as an object and not a string. Once you created this new representation of your DataTable, you can let the serializer take care of the rest. Here's how you could write such a converter: Class MyDataTableConverter Inherits JsonConverter Public Overrides Function CanConvert(type As Type) As Boolean Return type = GetType(DataTable) End Function Public Overrides Sub WriteJson(writer As JsonWriter,

Categories : Vb.Net

Convert a DataTable to IList
Perhaps (works also if the table contains more rows): IList<Foo> data = table.AsEnumerable() .SelectMany(r => table.Columns.Cast<DataColumn>() .Select(col => new Foo { Name = col.ColumnName, Value = r.IsNull(col) ? null : r[col].ToString() })) .ToList();

Categories : Linq

How to convert datatable to dictionary in ASP.NET/C#
The tricky thing here is the composite key (ClassID, ClassName). Once you identify that, it's easy to search this site for the solution. I'd recommend using tuples as pointed out here: Composite Key Dictionary

Categories : C#

Convert type of a columns in datatable
When importing the csv file if you already know the column types beforehand then you should make a table with those columns and then fill the data. Cloning a table and then filling the data again is very slow process especially if data is large You can refer to the following http://social.msdn.microsoft.com/Forums/windows/en-US/34b6a1e8-5103-42a3-aa45-cdc0cea461f2/importing-csv-file-to-datatable-problem-with-converting-data-type

Categories : String

Convert BindingSource to Datatable or Dataset
Try this DataSet ds = new DataSet(); foreach(DataGridViewColumn col in dgv.Columns) ds.table[0].Columns.Add(col.HeaderText, typof(string)); foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { ds.table[0].Rows[row.Index][cell.ColumnIndex] = cell.Value; } }

Categories : Sql Server

How to convert linq query into a datatable
Selecting off an anonymous type is going to frustrate you down the road when you actually want to know what object is selected in your gridview. Just select your DataItem and bind it to your gridview, and set up your Binding on the gridview to show columns for the properties you want to display in the gridview. //Obviously this is simplified and doesn't include your users stuff, but I think you get the idea. var allProjectItems = (from x in db.DateItems where x.Date.ProjectId == projectId select x).ToList(); You will have to set up your bindings on your gridview to show the data you want. As for the user business, I'd set up a partial class on the DataItem that will use navigational properties to get the user and return the values you want.

Categories : C#

How to Convert DataTable Column values from One Unit to another in C#?
You will need to keep the conversion data in some sort of container, for example to keep a matrix of values where each row will use for from unit and each column will for to unit (so if x==y the value will be 1 since converting from any unit to the same unit is multiplying it by one) After you have the matrix your code will look like: double value_to_convert = Double.Parse(strToConvert); return (value_to_convert* mat[from][to]).ToString();

Categories : C#

convert linq query results to datatable C#
First declare a new DataTable and add columns, in this : DataTable dt = new DataTable(); dt.Columns.Add("FirstName"); dt.Columns.Add("LastName"); DataRow row = null; Now I simply iterate through the query and fill a DataTable: foreach (var rowObj in query) { row = dt.NewRow(); dt.Rows.Add(rowObj.FirstName, rowObj.LastName); }

Categories : Asp Net

Convert GridView.DataSource with DateTime column to datatable
Try this way DataView dv=(DataView) from test in db.Tests select new { testId= test.TestId, courseName = test.Course.Name, onDate = test.OnDate, lastRegisterDate = test.LastRegisterDate }; gridAllTests.DataSource = dv; DataTable dt = new DataTable(); DataSourceSelectArguments args = new DataSourceSelectArguments(); DataView dv = new DataView(); dv = (DataView)dv.Select(args);// This SqlDataSourceObject means your sql query return object ,like dataset or datavi

Categories : C#

Json with datatable
Try changing: "sAjaxSource": data, To this: "sAjaxSource": '/php/connect/searchtablequery.php', Try also adding: "bServerSide": true, Edit 1: $(document).ready( function() { $('#example').dataTable( { "sAjaxSource": "http://www.sprymedia.co.uk/dataTables/json.php" } ); } ) Ref. http://datatables.net/usage/options Edit 2: As shown in my jsfiddle http://jsfiddle.net/HEDvf/667/ your JSON is different from mine. I don't know if it makes a difference, but I would try changing it. Here is mine: { "calldate": "2013-08-14 11:41:28", "clid": ""name name" <1002>", "src": "1002", "dst": "8834404", "dcontext": "from-internal", "channel": "SIP/1002-00000000", "dstchannel": "IAX2/voipms-6749", "lastapp": "Dial", "lastdata": "IAX2/voipms/

Categories : PHP

What's the best way to jSON serialize a .NET DataTable in WCF?
According to the chart on its homepage, Json.NET is really your only option - you can quickly get it from NuGet. Fortunately it's a great library and very easy to use. string json = JsonConvert.SerializeObject(myDataSet, new DataSetConverter()); Note that Rich Strahl has a great post with more details, and he also includes some custom work he did to use JavaScriptSerializer with (rather extensive) custom converters for the sake of comparison.

Categories : Dotnet

convert timestamp to date/hour/minute from database to datatable php mysql
Just use PHP standard date function <td><?= date('d/m/Y (H:i:s)', $row['upload_time']) ?></td>

Categories : PHP

can not parsing json data to datatable
Without provided more error information (such as console errors) or an example of it live, there's not much we can do. But at a quick guess, your aaData key uses the parsed JSON which also contains some non-data fluff (i.e. sEcho). Assumingly that parameter only wants to receieve the aaData of your source. So try changing: "aaData": $.parseJSON(data), to "aaData": $.parseJSON(data).aaData, Note: it would probably be best practice to parse the jSON outside of the datatable initialiser and check the aaData key exists before trying to use it. But the above code should work to tell you if the error is what i think it is

Categories : Java

Datatable populated by null, not by JSON
aaData is an array of array. So aaData should look more like: x = [["test", "test", "test"],["id", "status", "date"],["123", "456", "789"]]; If you want to create this from your data: //jsonList = you array of json objects x = []; for(var i = 0; i < jsonList.length; i++){ x.push([jsonList[i].ID, jsonList[i].status, jsonList[i].date]); }

Categories : Jquery

populate datatable from a local json file
Looks like the problem could be that your ajax is loading and setting the myObject variable but it is done after Datatables initialized so it does not get the updated myObject variable after your request has finished. You could do something like this to fix that: var myObject; $.ready(function(){ myObject={}; $.getJSON('http://localhost:8080/jsontext.json', function(data){ /* here I have tried using both the paths the c:pathjsontext.json and the one above */ myObject=data; $('#example').dataTable().fnAddData(myObject); }); });

Categories : Javascript

Cannot implicitly convert type System.data.datatable to Microsoft.Office.Interop.Excel
a DataTable type exists in both namespaces: Microsoft.Office.Interop.Excel and System.Data which are imported into your file. You have to explicitly reference the correct namespace for the return type of populateVendorGridView: public System.Data.DataTable populateVendorGridView() { ...

Categories : C#

Convert JSON String into JSON Array and show in ListView
Let's reformat that for a start. { "S29N": { "deleteToken": "IL5STLhq", "filename": "Stockholmsyndromet.docx", "infoToken": "joRm6p", "sha1": "b4a03897121d0320b82059c36f7a10a8ef4c113d", "size": 129332 }, "S8tf": { "deleteToken": "gzHTfGcF", "filename": "Screen_Shot_2013-07-02_at_3.52.23_PM.png", "infoToken": "wCfhXe", "sha1": "8c4e2bbc0794d2bd4f901a36627e555c068a94e6", "size": 122484 }, "error": "" } So what you seem to be trying to achieve is to iterate over the objects like S29N, S8tf and any other provided they are really objects. This is doable with something like this (code is not tested): // let's say sourceString is the variable holding the JSON text JSONObject request = new JSONObject(sourceString); for (Iterator keyIterator = r

Categories : Android

How to add multiple json values in a single cell of dataTable
Prior to DataTables 1.10.x, you could use the mRender parameter like this: "aoColumns":[ {"mData":"LastName", "sClass":"left", "mRender":function(data, type, full){ return full.FirstName + full.LastName + full.MiddleInitial; } }, {"mData":"ServiceDate","sClass":"left"}, {"mData":"ChargeAndDx","sClass":"left"}, {"mData":"BillingProvider","sClass":"left"}, {"mData":"null","sClass":"center","sDefaultContent":"<a href='' class='editor_menu'>menu</a>"} ] Starting from DataTables 1.10.x, you could use the columns.render property like this: "columns":[ {"data":"LastName", "className":"left", "render":function(data, type, full, meta){ return full.FirstName + full.LastName + full.MiddleInitial; } }, {"data":"Ser

Categories : Jquery

How to force json.net to deserialize DataTable column from integer to float
The problem you are facing is that by default, the Json.Net DataTableConverter which is used to serialize and deserialize the DataTable type, uses the first object within the json string to detect the type of the value for each column. Since YVar on the first object is an integer, then it assumes all other objects will be integers as well on that column. You have 2 options: Format your values as floats even when they are int values, in this case, your json string should have "YVar": 1.0 instead of "YVar": 1 Take json.net DataTableConverter source and tailor it to your needs. This would require you to use the overload of JsonConvert.DeserializeObject(string value, Type type, params JsonConverter[] converters)

Categories : C#

convert json to another json format
Use var obj = jQuery.parseJSON() to parse your input string. You can access the fields via obj.[FIELDNAME] and build your outputstring.

Categories : Jquery

Throw ajax error incase of custom exception using JSON object while populating datatable using datatables jquery plugin
It seems you need to use the fnServerData callback. I have never used it myself, but it seems you can manually do the ajax request and catch any server-side errors you want. In your case it would be something like this: $(document).ready( function() { try { $('#example').dataTable( { "bProcessing": true, "bServerSide": true, "sAjaxSource": "xhr.php", "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { oSettings.jqXHR = $.ajax( { "dataType": 'json', "type": "POST", "url": sSource, "data": aoData, "success": function(response) { //do error checking here, maybe "throw new Error('Some error')" based on data; fnCallback(

Categories : Jquery

Primefaces Datatable lost text in Filter field after datatable update
You can't (PrimeFaces 3.5) directly bind datatable filters with JSF bean, so they will not be preserved when you update the whole component. But if you call filter() on datatable widget, the data will be reloaded from server, without re-rendering the whole datatable component (so the filters will be preserved) <p:dataTable .... widgetVar="myTable"> ...</p:dataTable> <p:commandButton action="#{myBean.doSth}" .... oncomplete="myTable.filter()"/>

Categories : JSF

Insert DataTable rows to DataBaseTables using DataAdapter: leave out one column in DataTable
string qry = "select * from PurchaseProduct where 0 = 1"; sa = new SqlDataAdapter(qry, conn); dataSet = new DataSet(); sa.Fill(dataSet); dataSet.Tables[0].Columns.Add("dtcolnPurchaseProductProductName",typeof(string));

Categories : Misc

adding results of query against datatable to a column in another datatable in visual basic
You can always nest that in another query: select *, datediff(ms, startDate, endTime) from ( <your existing query here> ) t And while I'm here, it seems you need a lesson in parameterized queries: Dim result As New DataTable Dim Sql As String = _ "SELECT *, datediff(ms, startDate, endTime) FROM (" & _ "SELECT ID, startDate, codeID, Param, " & _ "(select top 1 startDate from myTable " & _ "where ID= @ID and Param = mt.param and codeID = 82 and startDate >= @startDate and startDate >=mt.startDate " & _ "ORDER BY startDate) endTime " & _ " FROM myTable mt " & _ " WHERE ID = @ID AND startDate between @startDate AND @endDate AND codeID = 81" & _ ") t" Using cn As New SqlConnection("c

Categories : SQL

For Loop of Datatable.rows breaks while exporting Datatable to excel in C# .Net
If I might offer an alternative: Use EPPLUS and its great LoadFromDataTable* Function - this would reduce your code to one line, it is magnitudes faster and it does not rely on Excel directly. Also: the library is free and can be included without licensing problems.

Categories : C#

JSF Primefaces datatable, first cell of first row is using previous datatable value when Columns tag is used
I have solved the problem. The issue seems to be when you create dynamic primefaces:datatables that use the primefaces:columns tag. When the data tables are created within a ui:repeat tag or using the primefaces:accordianPanel's looping ability, then every data table created after the first has a wrong value in the first cell of the first row. All other cells in the data table have the correct values. I have also noticed that the headerText is wrong and always from the previous data tables headerText (The first data table's headerText is always right). To solve this issue I placed the jstl:forEach tag inside of the primefaces:accordianPanel tag. This fixed the issue. It seems to be an issue with how the ui:repeat and/or the primefaces:accordianPanel is rendering the data tables. Here is t

Categories : JSF

Is there a way to create a datatable from an sql query and use datatable jquery filtering for it?
What happens when your javascript is called? Anything in the debugging Console window? You should attach your dataTable() call function to an event handler, like this: <script> $(document).ready(function () { $('#<%=GridView1.ClientID%>').dataTable(); }); </script> Have you checked the rendered HTML element to see if the table has and elements? I think JS dataTable requires it.

Categories : C#

Create line chart using Google Chart API and JSON for DataTable
The problem is a very small typo. In the JSON, row should be rows. Eg, changing the example JSON to var result = { "cols":[ {"type":"string"}, {"type":"number"}], "rows":[ {"c":[{"v":"20-01-13"}, {"v":22}]}, {"c":[{"v":"21-01-13"}, {"v":24}]}, {"c":[{"v":"22-01-13"}, {"v":27}]} ]}; and your code works : Update Look at Format of the Constructor's JavaScript Literal data Parameter You need to wrap each "c"-section into brackets and also misses "v" (value indicator) for the first column. Your updated test JSON is "cols": [ {"type":"string"},{"type":"number"} ], "rows":[ {"c":"20-01-13"},{"v":35}, {"c":"21-01-13"},{"v":30} ] } giving a "can't read 0 of undefined", becuase it should be { "cols":[ {"type":"string"},{"type":"number"} ], "rows":[

Categories : Javascript

Compare one datatable's rows to another datatable's columns
Not tested, but a simple loop on the dtReport columns collection checking if dtHeader columns collection contains a equal named column. If not remove the column from dtReport. SqlCommand cmdHeader = new SqlCommand("SELECT * FROM Header", conn); SqlCommand cmdReport = new SqlCommand("SELECT * FROM Report", conn); DataTable dtHeader = new DataTable(); DataTable dtReport = new DataTable(); SqlDataAdapter da1 = new SqlDataAdapter(cmdHeader); da1.Fill(dtHeader) SqlDataAdapter da2 = new SqlDataAdapter(cmdReport); da2.Fill(dtReport); for(int x = dtReport.Columns.Count - 1; x >= 0; x--) { DataColumn dc = dtReport.Columns[x]; if(!dtHeader.Columns.Contains(dc.ColumnName)) dtReport.Columns.Remove(dc.ColumnName); } The tri

Categories : C#

quickly Remove row from datatable which not find in another datatable
Try this (not tested), This should return you the list of rows those are both in dt1 and dt2 on the basis of id column (I am considering your id and id2 column is of type string) var rows = (from r1 in dt1.AsEnumerable() join r2 in dt2.AsEnumerable() on r1.Field<string>("id") equals r2.Field<string>("id2") select r1).ToList();

Categories : C#

How to delete row from specific datatable among multiple datatable?
This is how i pass data from one datatable to another (im using jquery 1.9) i assign oTable as a global javascript variable, then my table data as an object declared at the doc ready var oTable; $(document).ready(function() { var passData ={}; $(document).on("click", "#example tbody tr", function(){ var aPos = oTable.fnGetPosition(this); passData = oTable.fnGetData(aPos); }); passData is now available throughout my other doc ready event declarations after i have clicked on a row $('#someDiv').on('click', function(){ someFunction(passData); }); For your issue though, which i assume has a delete button on each row, i was thinking to set position as a variable aPos, global to the document ready, then executing your delete function var oTable; $(document).r

Categories : Jquery



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.