0
C#で2つのDataTableをlinqで結合する必要があります。どうすれば 'Invalidcastexception'を解決できますか
ここに貼り付けました。Invalidcastexception
です。
私はどのようにこの問題を解決できるかわかりません。
MySqlCommand cmdDataBaseKK = new MySqlCommand(" Select Date, Value as 'ValueK' from htdbmain.mainfsdb where field = 'KK' and ticker = '" + FinalTicker + "'", conn);
MySqlCommand cmdDataBaseJJ = new MySqlCommand(" Select Date, Value as 'ValueJ' from htdbmain.mainfsdb where field = 'JJ' and ticker = '" + FinalTicker + "'", conn);
DataTable DatasetJK = new DataTable();
try
{
MySqlDataAdapter sdaK = new MySqlDataAdapter();
sdaK.SelectCommand = cmdDataBaseKK;
DataTable DatasetK = new DataTable();
sdaK.Fill(DatasetK);
MySqlDataAdapter sdaJ = new MySqlDataAdapter();
sdaJ.SelectCommand = cmdDataBaseJJ;
DataTable DatasetJ = new DataTable();
sdaJ.Fill(DatasetJ);
//DatasetK.Merge(DatasetJ);
DataTable Table3 = new DataTable();
Table3.Columns.Add("Date", typeof(String));
Table3.Columns.Add("ValueK", typeof(Int32));
Table3.Columns.Add("ValueJ", typeof(Int32));
var Result =
from row1 in DatasetK.AsEnumerable()
join row2 in DatasetJ.AsEnumerable()
on row1.Field<String>("Date") equals row2.Field<String>("Date")
select Table3.LoadDataRow(new object[]
{
row1.Field<String>("Date"),
row1.Field<Int32>("ValueK"),
row2.Field<Int32>("ValueJ"),
}, false);
Result.CopyToDataTable();
BindingSource KSource = new BindingSource();
KSource.DataSource = Table3;
dataGridView1.DataSource = KSource;
単純な条件で試したのと同じデータテーブルが動作しています!
DataTable table1 = new DataTable();
table1.Columns.Add("Date", typeof(Int32));
table1.Columns.Add("ValueK", typeof(Int32));
table1.Rows.Add(1, 10);
table1.Rows.Add(2, 20);
table1.Rows.Add(3, 30);
DataTable table2 = new DataTable();
table2.Columns.Add("Date", typeof(Int32));
table2.Columns.Add("ValueJ", typeof(Int32));
table2.Rows.Add(1, 5);
table2.Rows.Add(2, 15);
table2.Rows.Add(3, 25);
DataTable table3 = new DataTable();
table3.Columns.Add("Date", typeof(Int32));
table3.Columns.Add("ValueK", typeof(Int32));
table3.Columns.Add("ValueJ", typeof(Int32));
var a = from row1 in table1.Rows.Cast<DataRow>()
join row2 in table2.Rows.Cast<DataRow>()
on row1["Date"] equals row2["Date"]
select table3.LoadDataRow(new object[]
{
row1.Field<Int32>("Date"),
row1.Field<Int32>("ValueK"),
row2.Field<Int32>("ValueJ"),
}, false);
a.CopyToDataTable();
BindingSource KSource = new BindingSource();
KSource.DataSource = table3;
dataGridView1.DataSource = KSource;
2つのコードセクションの違いは何ですか?
。 – user2657943
最初にすること:そのようなSQLの構築をやめてください。これはSQLインジェクション攻撃に開放されています。あなたは本当にそれに注意を払う必要があります、*今は*。 –
次に、* minimal *の例を作りましょう。問題を見るには本当に2つのテーブルが必要ですか? –