logo
down
shadow

How to execute DataTable.Select() for a column of custom class type for a particular element in that C#


How to execute DataTable.Select() for a column of custom class type for a particular element in that C#

By : user3100159
Date : January 12 2021, 01:40 AM
hop of those help? DataTable.Select(string) method cannot search for arbitrary types.
Implement the ToString method in ColorWithIndex class. For example:
code :
public override string ToString()
{
    return Color.Name + " " + Index;
}
dataTable.Select("CONVERT(ColorColumn, System.String) = '" + greenOne + "'")


Share : facebook icon twitter icon
How to get custom class in DataTable column displayed as class.ToString() in GridView?

How to get custom class in DataTable column displayed as class.ToString() in GridView?


By : vampyra fjarnskaggl
Date : March 29 2020, 07:55 AM
hop of those help? Your question is missing some details, but here a working example based on the assumption that Tables.PlantWADSUnitsList has the following structure:
code :
public class PlantWADSUnitsList
{
  public string Name { get; set; }
  public string Desc { get; set; }

  public override string ToString()
  {
    return Name + ": " + Desc;
  }
}
<asp:GridView ID="gvPlantWADS" runat="server" />
<asp:GridView ID="gvPlantWADS" runat="server" AutoGenerateColumns="false">
  <Columns>
    <asp:BoundField HeaderText="Category" DataField="Category" />
    <asp:BoundField HeaderText="Quantity" DataField="Quantity" />
    <asp:BoundField HeaderText="Units" DataField="Units" />
  </Columns>
</asp:GridView>
DateTime column type becomes String type after deserializing DataTable property on Custom Class

DateTime column type becomes String type after deserializing DataTable property on Custom Class


By : OlgaBarati
Date : March 29 2020, 07:55 AM
will be helpful for those in need The problem seems to be that Newtonsoft's DataSetConverter hardcodes using Newtonsoft's DataTableConverter by doing DataTableConverter converter = new DataTableConverter(); and then calling its ReadJson() method directly. Thus your converter is never used.
One solution would be to create your own version of DataSetConverter as well by adapting James Newton-King's original code:
code :
public class DataSetConverter<TDataTableConverter> : DataSetConverter where TDataTableConverter : JsonConverter, new()
{
    // This code adapted from 
    // https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Converters/DataSetConverter.cs
    // Copyright (c) 2007 James Newton-King
    // Licensed under The MIT License (MIT):
    // https://github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.md

    readonly TDataTableConverter converter = new TDataTableConverter();

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return null;
        }

        // handle typed datasets
        DataSet ds = (objectType == typeof(DataSet))
            ? new DataSet()
            : (DataSet)Activator.CreateInstance(objectType);

        reader.ReadAndAssert();

        while (reader.TokenType == JsonToken.PropertyName)
        {
            DataTable dt = ds.Tables[(string)reader.Value];
            bool exists = (dt != null);

            dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer);

            if (!exists)
            {
                ds.Tables.Add(dt);
            }

            reader.ReadAndAssert();
        }

        return ds;
    }
}

public static class JsonReaderExtensions
{
    public static void ReadAndAssert(this JsonReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException();
        if (!reader.Read())
        {
            new JsonReaderException(string.Format("Unexpected end at path {0}", reader.Path));
        }
    }
}
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// ...
private static Type GetColumnDataType(JsonReader reader, string columnName)
{
    JsonToken tokenType = reader.TokenType;

    switch (tokenType)
    {
        case JsonToken.String:
            if (columnName.IndexOf("date", StringComparison.OrdinalIgnoreCase) >= 0)
                return typeof(DateTime);
            return reader.ValueType;

        case JsonToken.Integer:
        case JsonToken.Boolean:
        case JsonToken.Float:
        case JsonToken.Date:
        case JsonToken.Bytes:
            return reader.ValueType;

        case JsonToken.Null:
        case JsonToken.Undefined:
            if (columnName.IndexOf("date", StringComparison.OrdinalIgnoreCase) >= 0)
                return typeof(DateTime);
            return typeof(string);

        case JsonToken.StartArray:
            reader.ReadAndAssert();
            if (reader.TokenType == JsonToken.StartObject)
            {
                return typeof(DataTable); // nested datatable
            }

            Type arrayType = GetColumnDataType(reader, columnName);
            return arrayType.MakeArrayType();
        default:
            throw JsonSerializationException.Create(reader, "Unexpected JSON token when reading DataTable: {0}".FormatWith(CultureInfo.InvariantCulture, tokenType));
    }
}
Type columnType = GetColumnDataType(reader, columnName);
How to select the first element of a column of type array column using knex.select()?

How to select the first element of a column of type array column using knex.select()?


By : mattversteegen
Date : March 29 2020, 07:55 AM
this will help Try using the first() function. It returns the first row in your table (in whatever order the table is sorted). The .select('images') will limit the columns returned to just images.
code :
knex
  .select('images')
  .table('items')
  .first()
  .then((data) => {
    // first row of 'images' is an array.
    // return only the first item in array.
    res.send(data[0]);
})
DataTable Column with Custom Data Type

DataTable Column with Custom Data Type


By : user3792566
Date : March 29 2020, 07:55 AM
this one helps. Yes you can create a column using a custom data type.
Assuming that you want a property to be of type Address:
How to execute Datatable.Select() query for a column of type System.Color?

How to execute Datatable.Select() query for a column of type System.Color?


By : Yuichiro Sato
Date : January 02 2021, 06:48 AM
this will help DataTable.Select supports column expressions syntax, including CONVERT function. As it turns out, CONVERT works for columns of type System.Drawing.Color as well.
Something like this should work:
code :
DataRow[] queried = table.Select("CONVERT(ColorColumn, System.String) = 'Color [Red]'");
var filterColor = Color.Red;
var queried = table.Select($"CONVERT(ColorColumn, System.String) = '{filterColor}'");
using System;
using System.Data;
using System.Drawing;
using System.Linq;

class Program
{
    private static void Main()
    {
        var table = new DataTable();
        table.Columns.Add(new DataColumn("Name", typeof(string)));
        table.Columns.Add(new DataColumn("Color", typeof(Color)));
        table.Rows.Add("First", Color.Red);
        table.Rows.Add("Second", Color.DarkRed);
        table.Rows.Add("Third", Color.Green);
        table.Rows.Add("Fourth", Color.Red);
        table.Rows.Add("Fifth", Color.Yellow);
        var filterColor = Color.Red;
        var queried = table.Select($"CONVERT(Color, System.String) = '{filterColor}'");
        //First, Fourth
        Console.WriteLine(string.Join(",", queried.Select(r => r["Name"])));
        Console.Read();
    }
}
Related Posts Related Posts :
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Loading a pop up page in ASP.net through a js file
  • How to pass alert or notification message from controller to View?
  • C# to pause, turn on ssas server, backup cube.... how to?
  • how to connect mysql8.0 with C#
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • How to convert API Json response to C# Array?
  • Blazor Textfield Oninput User Typing Delay
  • Performing both layout and render transform results in wrong output
  • uwp beforetextchanged cursor moving in front of text
  • How to keep duplicates from a string[] exclude words from a List and print them out
  • .Net Core Strings.Asc/Mid/Chr/Len missing even after importing Microsoft.VisualBasic
  • How to return to previous search page without being asked to Confirm Form Re-submission and keeping the results on ASP.N
  • How set a identity scaffolding item/page how initial page in asp.net MVC core?
  • LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
  • What is "ByteArray.uncompress()" in AS3 equivalent to in C#?
  • Getting a specific letter from a string variable for my simple guessing game for clues
  • Send an email with Outlook without a subject --- dialog box issue
  • passing List<MyModel> from my controller in the "WebInterfaceProject" to the processor method in "D
  • How to convert Word document created from template by OpenXML into MemoryStream?
  • How can I make a single slider that changes the color of an object?
  • Remap JSON parameter in c#
  • What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension met
  • Convert OpenSSL encryption into native C#
  • Accessing Properties in Razor Pages
  • How to get SOAP element value
  • Projection after Group
  • C# error cannot convert sytem.text.regularexpressions.match to string
  • Issues with Save/Load System in a Text Based Adventure game made with ScriptableObjects in Unity
  • VS2019 MSBuild.exe - ASP .Net MVC project fails to publish when using PublishProfile, but works when using OutDir parame
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • Attempt to invoke virtual method on a null object reference Xamarin LockScreen
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org