|
I used your algorithm and it solved my problem. Now, I want to deliver the filtered table into a new DataTable. I used this:
DataTable filteredTable = dv.ToTable();
When I debug the code, there is some information in dv table but filteredTable is empty. Why?
|
|
|
|
|
Firstly, a DataView isn't a table - it is a filtered view of a table and that's quite different in reality.
Secondly, it works fine for me:
private void TwoDGVs_Shown(object sender, EventArgs e)
{
string strConnect = SMDBSupport.SMInstanceStorage.GetInstanceConnectionString(DBName);
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(strConnect))
{
try
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM MyTable", con))
{
da.SelectCommand.Parameters.AddWithValue("@SEARCH", "The text to search for");
da.Fill(dt);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
DataView dv = new DataView(dt);
Source.DataSource = dv;
}
private void Filter_TextChanged(object sender, EventArgs e)
{
if (Source.DataSource is DataView dv)
{
dv.RowFilter = $"Title LIKE '%{Filter.Text}%'";
DataTable dt = dv.ToTable();
Destination.DataSource = dt;
}
}
I get two DGV's, one looking a all rows, the other filtered.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Might be slightly more compact to do
Column2 IN ('{checked_item2.Join("', '")}')" this would also be impervious to changing the no of checkboxes
I've not tested this.
I am assuming that the filter texts are fixed (i.e. the user cannot change them). Also beware if any values have an ' in them - the ' have to be doubled.
|
|
|
|
|
Hi,
My DataTable has 40 columns. I have created a Database and a table with 40 columns for SQLite programmatically.
I want to copy all my contents in DataTable into SQLite table. I used this class code:
public class SQLiteFunction
{
public string databaseName { get; set; }
public string dataTableName { get; set; }
private DataTable dt = new DataTable();
public SQLiteFunction()
{
dt.TableName = dataTableName;
}
public void Create_db()
{
if (!File.Exists(databaseName))
{
using (var sqlite = new SQLiteConnection(@"Data Source=" + databaseName))
{
sqlite.Open();
string script = File.ReadAllText(@"CreateTable.sql");
SQLiteCommand command = new SQLiteCommand(script, sqlite);
command.ExecuteNonQuery();
sqlite.Close();
}
}
}
public void InsertData()
{
SQLiteConnection con = new SQLiteConnection(@"Data Source=" + databaseName);
con.Open();
SQLiteDataAdapter dAdapter = new SQLiteDataAdapter("SELECT FROM MyTable", con);
SQLiteCommandBuilder cmdBuilder = new SQLiteCommandBuilder(dAdapter);
dAdapter.Fill(dt);
}
}
When I use InserData() method, there is no runtime error but my SQLite table is still empty.
Please help me.
|
|
|
|
|
Your InsertData method is reading data from the DEL - a SELECT query - instead of trying to write data to the DB - an INSERT query.
Have a look here: DataAdapter.Update(DataSet) Method (System.Data.Common) | Microsoft Docs[^]
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I changed the InserData() method:
public void InsertData()
{
SQLiteConnection con = new SQLiteConnection(@"Data Source=" + databaseName);
con.Open();
SQLiteDataAdapter dAdapter = new SQLiteDataAdapter("INSERT INTO MyTable", con);
SQLiteCommandBuilder cmdBuilder = new SQLiteCommandBuilder();
cmdBuilder.DataAdapter = dAdapter;
dAdapter.Update(dt);
con.Close();
}
It still doesn't work. Note that DataTable headers and column names in SQLite table are the same.
What query should I use?
modified 27-Jul-21 3:24am.
|
|
|
|
|
Is there any way to transfer them from DataTable to SQLite table at once and quickly?
I can use For loop but my data is huge (40 columns and around 30000 rows).
|
|
|
|
|
Yes. And if you follow the link I gave you it tells you how to!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
In the Link you provided, there is a string parameter for queryString. I need to INSERT data. What query should I use for transferring all cell information into SQLite?
|
|
|
|
|
It looks to me like the query string should be the SELECT query that pulls the data you want to transfer.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
I created a client to communicate with RTD server, my knowledge is small in C# I have greater in JAVA, but I didn't find anything likely to be used in JAVA, I'm using this example of a C# client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace DotNet2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
chamaMetodo("RTDTrading.RTDServer");
}
private static void chamaMetodo(string v)
{
RtdClient rtd = new RtdClient(v);
Console.WriteLine("rtd:"+rtd);
object[] param = new Object[2];
param[0] = "DOLFUT_F_0";
param[1] = "HOR";
Object ret = rtd.GetValue(param);
Console.WriteLine("ret:"+ret);
}
}
}
Class Interface que monta a comunicação:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace DotNet2
{
public interface IRtdClient
{
object GetValue(params object[] args);
}
public class RtdClient : IRtdClient
{
readonly string _rtdProgId;
static IRtdServer _rtdServer;
public RtdClient(string rtdProgId)
{
_rtdProgId = rtdProgId;
}
public object GetValue(params object[] args)
{
const int topicCount = 1;
var rnd = new Random();
var topicId = rnd.Next(int.MaxValue);
var rtdServer = GetRtdServer();
Console.WriteLine("TopicID "+topicId+" args:"+args[0]+" args2:"+args[1]);
rtdServer.ConnectData(topicId, args, true);
object val = null;
while (val == null)
{
var alive = rtdServer.Heartbeat();
if (alive != 1)
GetRtdServer();
else
{
var refresh = rtdServer.RefreshData(topicCount);
if (refresh.Length <= 0) continue;
if (refresh[0, 0].ToString() == topicId.ToString())
{
val = refresh[1, 0];
}
}
}
rtdServer.DisconnectData(topicId);
return val;
}
IRtdServer GetRtdServer()
{
if (_rtdServer == null)
{
Type rtd = Type.GetTypeFromProgID(_rtdProgId);
_rtdServer = (IRtdServer)Activator.CreateInstance(rtd);
}
return _rtdServer;
}
}
[ComImport,
TypeLibType((short)0x1040),
Guid("EC0E6191-DB51-11D3-8F3E-00C04F3651B8")]
public interface IRtdServer
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(10)]
int ServerStart([In, MarshalAs(UnmanagedType.Interface)] IRTDUpdateEvent callback);
[return: MarshalAs(UnmanagedType.Struct)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(11)]
object ConnectData([In] int topicId, [In, MarshalAs(UnmanagedType.SafeArray,
SafeArraySubType = VarEnum.VT_VARIANT)] ref object[] parameters, [In, Out] ref bool newValue);
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(12)]
object[,] RefreshData([In, Out] ref int topicCount);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(13)]
void DisconnectData([In] int topicId);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(14)]
int Heartbeat();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(15)]
void ServerTerminate();
}
[ComImport,
TypeLibType((short)0x1040),
Guid("A43788C1-D91B-11D3-8F39-00C04F3651B8")]
public interface IRTDUpdateEvent
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(10),
PreserveSig]
void UpdateNotify();
[DispId(11)]
int HeartbeatInterval
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(11)]
get; [param: In]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(11)]
set;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(12)]
void Disconnect();
}
}
But I'm getting this error, in the method call:rtdServer.ConnectData(topicId, args, true);
Unhandled exception. System.Runtime.InteropServices.COMException (0x8000FFFF): Falha catastrófica (0x8000FFFF (E_UNEXPECTED))
at DotNet2.IRtdServer.ConnectData(Int32 topicId, Object[]& parameters, Boolean& newValue)
Is anyone aware of the error?
modified 26-Jul-21 18:00pm.
|
|
|
|
|
I need help C# VS 2019 Windows Form Application. I am new!!!I want to shuffle an integer array and use the values on my buttons when I click on my ButtonNext. I have got some tips but not working.
- e is not accepted?
- shuffledArray[] is not accepted?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Windows.Forms;
namespace Dari1MainPage_v002
{
public partial class Exercise1 : Form
{
public Exercise1()
{
InitializeComponent();
}
private void btnNext_Click(object sender, EventArgs e)
{
int[] originalArray = { 0, 1, 2, 3 };
var rng = new Random();
var shuffledArray = originalArray.OrderBy(e => rng.NextDouble()).ToArray();
btnAns1.Text = shuffledArray[0];
btnAns2.Text = shuffledArray[1];
btnAns3.Text = shuffledArray[2];
btnAns4.Text = shuffledArray[3];
}
}
}
|
|
|
|
|
That code doesn't compile for two reasons:
1) It won't let you use e inside the OrderBy as it's already declared as a parameter to the function.
2) You can't implicitly convert an integer to a string.
Try this:
int[] originalArray = { 0, 1, 2, 3 };
var rng = new Random();
var shuffledArray = originalArray.OrderBy(oa => rng.NextDouble()).ToArray();
btnAns1.Text = shuffledArray[0].ToString();
btnAns2.Text = shuffledArray[1].ToString();
btnAns3.Text = shuffledArray[2].ToString();
btnAns4.Text = shuffledArray[3].ToString();
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Thanks it is working fine now
|
|
|
|
|
The values in your array are integers, but a Button.Text property requires a string. So add a call to ToString on your numbers thus:
btnAns1.Text = shuffledArray[0].ToString();
btnAns2.Text = shuffledArray[1].ToString();
btnAns3.Text = shuffledArray[2].ToString();
btnAns4.Text = shuffledArray[3].ToString();
|
|
|
|
|
Hi,
I want to explain my real-world problem with a simple example. I have these names and their corresponding marks:
Alex -----> 20
Alexis -----> 12.5
John -----> 16.3
Alex -----> 17.5
John -----> 19
I can sum each person's mark using Dictionary but I don't know how to find the average for them.
If there is any better way to find the average else than Dictionary, please guide me.
Thanks.
|
|
|
|
|
I finally could solve it by using two dictionaries. One for unique keys and another for any duplicates. After that, I could calculate the final result based on those two dictionaries. 
|
|
|
|
|
You could have added a counter to the "values" side of the dictionary: e.g.
Dictionary<string, Tuple<int, int>>.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
The simplest way is to create a dictionary that holds a tupple:
Dictionary<string, (int, double)> dict = new Dictionary<string, (int, double)>();
Then when you add your items, you check if the key name is already there.
If it isn't add it with a int of 1 as the count, and a double which is the value:
dict.Add("Alex", (1, 20.0));
If it is, increment the integer, and sum the new value :
dict["Alex"] = (dict["Alex"].Item1 + 1, dict["Alex"].Item2 + 17.5);
You can then work out the averages very simply in a loop when all items are added.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
In C# generic Dictionaries do not allow duplicate Keys.
You could use another data structure; for example:
List<KeyValuePair<string, double>> ScoreList = new List<KeyValuePair<string, double>>();
Once you've got all your data entered, to average use Linq:
double averageOfAll = ScoreList.Average(kvp => kvp.Value);
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
|
|
|
|
|
Hello Guys,
I need to build a comma separated string from 100+ different field(few are string and others are either int or decimal), here each field should be in specific order:
Solution i can imagine are:
1)Define a string builder and Call methods for each field to fill the string builder
2)build each item in list and then call for string.join
3) Call for string.Format...
I am not able to decide which method is more efficient and maintainable.
Any thought on this? may be better approach ?
|
|
|
|
|
There are plenty of CSV libraries in Nuget. Why roll another one when it's been a repeatedly solved problem?
|
|
|
|
|
In addition to the excellent advice that Dave gave you, there is an easy way to join any number of fields with a common delimiter.
If you have the fields in an array or a List<> object, you can call string.Join(",", Fields.ToArray())
That method gives you a single string with all the elements separated by commas.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
Depends on where the "100+" fields are coming from. Trying to spec a solution to an ill-defined problem.
(I'm currently using Excel to create "data tables" which are then exported as CSV files for use as embedded resources in another app).
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
Hi,
I'm using DevExpress Spreadsheet. I divide a number by another number and convert the result to string and then I put it in a cell in spreadsheet. The problem is that the output is an integer, not a double value. How can I fix it?
|
|
|
|
|