1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
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.Windows.Forms; namespace WindowsFormsApp1 { public class TestObserverDisposer : IDisposable { //監視対象を保持 public TestObservable observable; public TestObserverDisposer(TestObservable o) { this.observable = o; } public void Dispose() { observable.Observer = null; } } public class TestObservable : IObservable<int> { //監視側を保持 public TestObserver Observer; public void Excute() { if (Observer == null) return; Observer.OnNext(1); Observer.OnCompleted(); } public IDisposable Subscribe(IObserver<int> o) { Observer = (TestObserver)o; return new TestObserverDisposer(this); } } public class TestObserver : IObserver<int> { public void OnError(Exception e) { } public void OnCompleted() { } public void OnNext(int val) { MessageBox.Show(val.ToString()); } } public partial class Form1 : Form { public Form1() { InitializeComponent(); TestObserver observer = new TestObserver(); TestObservable observable = new TestObservable(); IDisposable disporser = observable.Subscribe(observer); observable.Excute(); disporser.Dispose(); observable.Excute(); } } } |
C# 仕入管理(仕入帳)業務用
業務に使えるソフトということで作成。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 |
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.Windows.Forms; using System.Data.OleDb; namespace WindowsFormsApp1 { public partial class main_form : Form { setting setting; public string form_type; public main_form parent_form; private void form_type_check() { setting_strings_main(); if (form_type == "parts") { setting_strings_parts(); this.Text = "材料手配マスタ"; this.FormClosed += new FormClosedEventHandler((object sender, FormClosedEventArgs e) => { if (null != parent_form) parent_form.Close(); }); } if (form_type == "parts_sub") { setting_strings_parts_sub(); this.Text = "材料手配テーブル"; } if (form_type == "copy") { setting_strings_copy(); this.Text = "複製"; } if (form_type == "supply") { setting_strings_supply(); this.Text = "仕入先マスタ"; } if (form_type == "sumup") { setting_strings_sumup(); this.Text = "集計表示"; } if (form_type == "size") { setting_strings_width(); this.Text = "幅設定"; } this.Width = setting.width; this.Height = setting.height; } public main_form(string f = "main", main_form p = null) { form_type = f; parent_form = p; InitializeComponent(); setting = new setting(); form_type_check(); db_setting db = new db_setting(setting); if (!db.load_check()) { foreach (Control c in this.Controls) c.Enabled = false; return; } setting.width_list = db.get_size_master(); setting.variable_type_dic = new Dictionary<string, string>(); for (int x = 0; x < setting.control_variable_type.GetLength(0); x++) { setting.variable_type_dic.Add(setting.control_variable_type[x, 0], setting.control_variable_type[x, 1]); } this.create_controls(); this.set_button_event(); this.set_control_focus_event(); this.set_combobox_items(); this.set_main_menu(); dgv_setting dgv = new dgv_setting(((DataGridView)this.Controls["グリッドビュー"]), setting,form_type); dgv.create_columns(); dgv.hide_columns(); dgv.read_only_columns(); dgv.change_flg_event(); dgv.basic_properties(); dgv.set_click_supplier_master_event(); dgv.set_click_context_event(); dgv.error_handle(); dgv.set_forcus_event(); if (form_type == "sumup") { dgv_load_sumup(); } else { dgv_load(); } } private void set_main_menu() { if (form_type != "main") return; MenuStrip ms = new MenuStrip(); ToolStripMenuItem tsm_menu; tsm_menu = new ToolStripMenuItem(); tsm_menu.Text = "仕入先マスタ(&S)"; tsm_menu.Click += new EventHandler((object sender, EventArgs e) => { main_form f = new main_form("supply", this); f.ShowDialog(); }); ms.Items.Add(tsm_menu); tsm_menu = new ToolStripMenuItem(); tsm_menu.Text = "幅設定(&W)"; tsm_menu.Click += new EventHandler((object sender, EventArgs e) => { main_form f = new main_form("size", this); f.ShowDialog(); }); ms.Items.Add(tsm_menu); this.Controls.Add(ms); } private void create_controls() { for (int x = 0; x < setting.control_lists.GetLength(0); x++) { Control ctrl = null; switch(setting.control_lists[x, 0]) { case "l": ctrl = new Label(); break; case "t": ctrl = new TextBox(); break; case "c": ctrl = new ComboBox(); break; case "b": ctrl = new Button(); break; case "d": ctrl = new DataGridView(); break; } ctrl.Name = setting.control_lists[x, 1]; ctrl.Top = int.Parse(setting.control_lists[x, 3]); ctrl.Left = int.Parse(setting.control_lists[x, 4]); ctrl.Width = int.Parse(setting.control_lists[x, 5]); ctrl.Height = int.Parse(setting.control_lists[x, 6]); if (setting.control_lists[x, 0] != "d") { ctrl.Text = setting.control_lists[x, 2]; ctrl.Font = new Font("MS UI Gothic", int.Parse(setting.control_lists[x, 7])); } if (setting.control_lists[x, 8] == "2") ctrl.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; this.Controls.Add(ctrl); } } private void dgv_load_sumup() { DataGridView dgv = (DataGridView)this.Controls["グリッドビュー"]; db_setting db = new db_setting(setting); db.main_table_attach_dgv2(build_query_sumup(), dgv); visible_display_sumup(); } private void dgv_load() { DataGridView dgv = (DataGridView)this.Controls["グリッドビュー"]; db_setting db = new db_setting(setting); db.main_table_attach_dgv2(build_query(), dgv); visible_display(); } private void visible_display_sumup() { DataGridView dgv = (DataGridView)this.Controls["グリッドビュー"]; for (int i = 0; i < setting.column_headers.Length; i++) { string t = setting.column_headers[i]; if (t != "金額" && t != "仕入先" && t != "部門" && t != "扱い" && t != "区分" && t != "税区分" && t != "仕入月") { dgv.Columns[t].Visible = false; } } } private void visible_display() { if (form_type != "main" && form_type != "copy") return; DataGridView dgv = (DataGridView)this.Controls["グリッドビュー"]; if (this.Controls["表示種類"].Text == "全部") { foreach (string h in setting.basic_headers) { dgv.Columns[h].Visible = true; } foreach (string h in setting.shipping_headers) { dgv.Columns[h].Visible = true; } foreach (string h in setting.material_headers) { dgv.Columns[h].Visible = true; } } if (this.Controls["表示種類"].Text == "材料・外注") { foreach (string h in setting.basic_headers) { dgv.Columns[h].Visible = true; } foreach (string h in setting.shipping_headers) { dgv.Columns[h].Visible = false; } foreach (string h in setting.material_headers) { dgv.Columns[h].Visible = true; } } if (this.Controls["表示種類"].Text == "運送") { foreach (string h in setting.basic_headers) { dgv.Columns[h].Visible = true; } foreach (string h in setting.shipping_headers) { dgv.Columns[h].Visible = true; } foreach (string h in setting.material_headers) { dgv.Columns[h].Visible = false; } } if (this.Controls["表示種類"].Text == "最小") { foreach (string h in setting.basic_headers) { dgv.Columns[h].Visible = true; } foreach (string h in setting.shipping_headers) { dgv.Columns[h].Visible = false; } foreach (string h in setting.material_headers) { dgv.Columns[h].Visible = false; } } } private void dgv_new_row() { DataGridView dgv = (DataGridView)this.Controls["グリッドビュー"]; for (int i = 0; i < dgv.Rows.Count; i++) { if(dgv.Rows[i].Cells[setting.id_header].Value == null) { dgv.Rows.Add(); return; } } dgv.Rows.Clear(); dgv.Rows.Add(); } private void set_combobox_items() { db_setting db = new db_setting(setting); if (form_type == "main"|| form_type == "parts") { foreach (string target_column_name in setting.supplier_master_header) { var cd_name_list = db.get_master_list2(target_column_name, setting.supplier_table_name); var name_list = cd_name_list.Select(x => x[1]).ToArray(); ((ComboBox)this.Controls[target_column_name]).Items.AddRange(name_list); } } if (form_type == "main" || form_type == "copy") { ComboBox ctrl = (ComboBox)this.Controls["表示種類"]; foreach (string col in setting.display_type) { ctrl.Items.Add(col); } ctrl.Text = setting.display_type[0]; ((ComboBox)this.Controls["表示種類"]).SelectedValueChanged += new EventHandler((object sender, EventArgs e) => { visible_display(); }); } if (form_type == "main" || form_type == "copy" || form_type == "parts" || form_type == "supply") { ComboBox ctrl = (ComboBox)this.Controls["一致種類"]; ctrl.Items.Add("曖昧"); ctrl.Items.Add("完全"); ctrl.Text = "曖昧"; } } private void set_control_focus_event() { for (int i = 0; i < setting.where_targes.Length; i++) { this.Controls[setting.where_targes[i]].KeyUp += new KeyEventHandler((object sender, KeyEventArgs e)=> { if (e.Control && e.KeyCode == Keys.Enter) { if (form_type == "main") { ((ComboBox)this.Controls["表示種類"]).Focus(); } ((Button)this.Controls["検索"]).PerformClick(); } }); this.Controls[setting.where_targes[i]].LostFocus += new EventHandler((object sender, EventArgs e) => { Control ctrl = (Control)sender; if (ctrl.Text == "") { ctrl.BackColor = SystemColors.Window; } else { ctrl.BackColor = Color.DodgerBlue; } }); } for (int i = 0; i < setting.where_date_target.Length; i++) { this.Controls[setting.where_date_target[i]].KeyUp += new KeyEventHandler((object sender, KeyEventArgs e) => { if (e.Control && e.KeyCode == Keys.Enter) { ((ComboBox)this.Controls["表示種類"]).Focus(); ((Button)this.Controls["検索"]).PerformClick(); } }); this.Controls[setting.where_date_target[i]].LostFocus += new EventHandler((object sender, EventArgs e) => { TextBox ctrl = ((TextBox)sender); if (ctrl.Text != "_") ctrl.Text = new parse_setting("d", ctrl.Text).parse_result; if (ctrl.Text == "") { ctrl.BackColor = SystemColors.Window; } else { ctrl.BackColor = Color.DodgerBlue; } }); this.Controls["_" + setting.where_date_target[i]].KeyUp += new KeyEventHandler((object sender, KeyEventArgs e) => { if (e.Control && e.KeyCode == Keys.Enter) { ((ComboBox)this.Controls["表示種類"]).Focus(); ((Button)this.Controls["検索"]).PerformClick(); } }); this.Controls["_" + setting.where_date_target[i]].LostFocus += new EventHandler((object sender, EventArgs e) => { TextBox ctrl = ((TextBox)sender); ctrl.Text = new parse_setting("d", ctrl.Text).parse_result; if (ctrl.Text == "") { ctrl.BackColor = SystemColors.Window; } else { ctrl.BackColor = Color.DodgerBlue; } }); } } private string sql_string_parse(string q) { q = q.Replace("'", "’"); return q; } public string build_query_sumup() { string[] updated_header = new string[setting.column_headers.Length]; for (int i = 0; i < setting.column_headers.Length; i++) { string t = setting.column_headers[i]; if (t == "金額") { updated_header[i] = "sum(金額) as 金額"; } else if (t == "仕入先" || t == "部門" || t == "扱い" || t == "区分" || t == "税区分" || t == "仕入月") { updated_header[i] = setting.column_headers[i]; } else { updated_header[i] = "'' as " + setting.column_headers[i]; } } string select = "select " + string.Join(",", updated_header) + " from " + setting.main_table_name; select = select + " group by 仕入先,部門,扱い,区分,税区分,仕入月"; string base_query = setting.main_form_instance.parent_form.build_query(); select = select.Replace(setting.main_table_name, "( " + base_query + " )"); return select; } public string build_query() { string match = "曖昧"; if (form_type == "main" || form_type == "copy" || form_type == "parts" || form_type == "supply") { match = ((ComboBox)this.Controls["一致種類"]).Text; } string select = "select " + string.Join(",", setting.column_headers) + " from " + setting.main_table_name; string where = ""; List<string> where_form_text = new List<string>(); for(int i = 0; i < setting.where_targes.Length; i++) { if (this.Controls[setting.where_targes[i]].Text == "_") { where_form_text.Add("(" + setting.where_targes[i] + " is null or " + setting.where_targes[i] + " = '')"); } else if (this.Controls[setting.where_targes[i]].Text != "") { if(match == "完全") { where_form_text.Add(setting.where_targes[i] + " = '" + sql_string_parse(this.Controls[setting.where_targes[i]].Text) + "'"); } else { where_form_text.Add(setting.where_targes[i] + " like '%" + sql_string_parse(this.Controls[setting.where_targes[i]].Text) + "%'"); } } } if(where_form_text.Count > 0) { where = " where "; for(int i = 0; i < where_form_text.Count; i++) { if(i == where_form_text.Count - 1) { where += where_form_text[i]; } else { where += where_form_text[i] + " and "; } } } List<string> where_date_form_text = new List<string>(); for (int i = 0; i < setting.where_date_target.Length; i++) { if (this.Controls[setting.where_date_target[i]].Text == "_") { where_date_form_text.Add(setting.where_date_target[i] + " is null"); } else if (this.Controls[setting.where_date_target[i]].Text != "" && this.Controls["_" + setting.where_date_target[i]].Text != "") { where_date_form_text.Add("(" + setting.where_date_target[i] + " >= #" + this.Controls[setting.where_date_target[i]].Text + "# and " + setting.where_date_target[i] + " <= #" + this.Controls["_" + setting.where_date_target[i]].Text + "#)"); } else if (this.Controls[setting.where_date_target[i]].Text != "" && this.Controls["_" + setting.where_date_target[i]].Text == "") { where_date_form_text.Add(setting.where_date_target[i] + " >= #" + this.Controls[setting.where_date_target[i]].Text + "#"); } else if (this.Controls[setting.where_date_target[i]].Text == "" && this.Controls["_" + setting.where_date_target[i]].Text != "") { where_date_form_text.Add(setting.where_date_target[i] + " <= #" + this.Controls["_" + setting.where_date_target[i]].Text + "#"); } } if (where_date_form_text.Count > 0) { if (where == "") { where = " where "; } else if (where != "") { where += " and "; } for (int i = 0; i < where_date_form_text.Count; i++) { if (i == where_date_form_text.Count - 1) { where += where_date_form_text[i]; } else { where += where_date_form_text[i] + " and "; } } } if (where != "") select += where; select += " order by ID"; //todo sql //MessageBox.Show(select); return select; } } public class setting { public main_form main_form_instance; public string connection_string; public string[] column_headers; public string id_header; public string[,] control_values; public string[,] control_variable_type; public Dictionary<string, string> variable_type_dic; public string[] where_targes; public string[] where_date_target; public string main_table_name; public string supplier_table_name; public string[] supplier_master_header; public string change_flg_header; public string[] hide_headers; public string[] read_only_headers; public string color_check_header; public string parts_table_name; public string[,] control_lists; public string[,] main_parts_correspond; public string[,] parts_sub_correspond; public int width; public int height; public string[] display_type; public string[] shipping_headers; public string[] material_headers; public string[] basic_headers; public List<string[]> width_list; } public class db_setting { setting setting; public db_setting(setting s) { setting = s; } public List<string[]> get_size_master() { List<string[]> size_master_list = new List<string[]>(); string sql = "select 対象フォーム,列名,幅 from 幅設定"; try { using (OleDbConnection con = new OleDbConnection(setting.connection_string)) { con.Open(); OleDbCommand cmd = new OleDbCommand(sql, con); using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { size_master_list.Add(new string[] { dr["対象フォーム"].ToString(), dr["列名"].ToString(), dr["幅"].ToString() }); } } } return size_master_list; } catch (Exception e) { MessageBox.Show(e.Message); return size_master_list; } } public bool load_check() { try { using (OleDbConnection con = new OleDbConnection(setting.connection_string)) { con.Open(); return true; } } catch (Exception e) { MessageBox.Show(e.Message); return false; } } private string sql_string_parse(string q) { q = q.Replace("'", "’"); return q ; } public void insert_update_dgv(DataGridView d) { List<int> insert_target_rows_index = new List<int>(); List<int> update_target_row_index = new List<int>(); List<DataGridViewRow> remove_target_rows = new List<DataGridViewRow>(); for (int i = 0; i < d.Rows.Count; i++) { if(d.Rows[i].Cells[setting.change_flg_header].Value != null && d.Rows[i].Cells[setting.change_flg_header].Value.ToString() == "1") { if(d.Rows[i].Cells[setting.id_header].Value == null) { insert_target_rows_index.Add(i); } else { update_target_row_index.Add(i); } remove_target_rows.Add(d.Rows[i]); } } foreach (int row_index in update_target_row_index) { List<string> header_values_list = new List<string>(); for (int c = 0; c < setting.column_headers.Length; c++) { if (d.Columns[c].HeaderText != setting.id_header && d.Columns[c].HeaderText != setting.change_flg_header) { string value = "null"; if (d.Rows[row_index].Cells[c].Value != null && d.Rows[row_index].Cells[c].Value.ToString() != "") { value = "'" + sql_string_parse(d.Rows[row_index].Cells[c].Value.ToString()) + "'"; } header_values_list.Add(d.Columns[c].HeaderText + "=" + value); } } string update_sql = "update " + setting.main_table_name + " set " + string.Join(",", header_values_list) + " where " + setting.id_header + " = " + d.Rows[row_index].Cells[setting.id_header].Value.ToString(); try { using (OleDbConnection con = new OleDbConnection(setting.connection_string)) { con.Open(); OleDbCommand cmd = new OleDbCommand(update_sql, con); cmd.ExecuteNonQuery(); } } catch (Exception e) { MessageBox.Show(e.Message); return; } } foreach (int row_index in insert_target_rows_index) { List<string> header_list = new List<string>(); List<string> values_list = new List<string>(); for (int c = 0; c < setting.column_headers.Length; c++) { if(d.Columns[c].HeaderText != setting.id_header && d.Columns[c].HeaderText != setting.change_flg_header) { if(d.Rows[row_index].Cells[c].Value != null && d.Rows[row_index].Cells[c].Value.ToString() != "") { header_list.Add(d.Columns[c].HeaderText); values_list.Add("'" + sql_string_parse(d.Rows[row_index].Cells[c].Value.ToString()) + "'"); } } } string insert_sql = "insert into " + setting.main_table_name + " (" + string.Join(",", header_list) + ", modified) values (" + string.Join(",", values_list) + ",'" + DateTime.Now.ToString() + "')"; try { using (OleDbConnection con = new OleDbConnection(setting.connection_string)) { con.Open(); OleDbCommand cmd = new OleDbCommand(insert_sql, con); cmd.ExecuteNonQuery(); } } catch (Exception e) { MessageBox.Show(e.Message); return; } } main_table_attach_dgv2(setting.main_form_instance.build_query(),d); } public List<string[]> get_master_list2(string target_column_name, string target_table_name) { List<string[]> master_list = new List<string[]>(); string sql = "select distinct " + target_column_name + "コード," + target_column_name + " from " + target_table_name + " where " + target_column_name + " is not null"; try { using (OleDbConnection con = new OleDbConnection(setting.connection_string)) { con.Open(); OleDbCommand cmd = new OleDbCommand(sql, con); using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { master_list.Add(new string[] { dr[target_column_name + "コード"].ToString(), dr[target_column_name].ToString() }); } } } return master_list; } catch (Exception e) { MessageBox.Show(e.Message); return master_list; } } public void main_table_attach_dgv2(string sql, DataGridView dgv) { dgv.Rows.Clear(); try { using (OleDbConnection con = new OleDbConnection(setting.connection_string)) { con.Open(); OleDbCommand cmd = new OleDbCommand(sql, con); using (OleDbDataReader dr = cmd.ExecuteReader()) { List<DataGridViewRow> rows = new List<DataGridViewRow>(); while (dr.Read()) { string[] new_row_values = new string[setting.column_headers.Length]; for (int i = 0; i < setting.column_headers.Length; i++) { if (setting.variable_type_dic.ContainsKey(setting.column_headers[i])) { parse_setting p; switch (setting.variable_type_dic[setting.column_headers[i]]) { case "d": p = new parse_setting("d", dr[setting.column_headers[i]].ToString()); new_row_values[i] = p.parse_result; break; case "m": p = new parse_setting("m", dr[setting.column_headers[i]].ToString()); new_row_values[i] = p.parse_result; break; case "z": p = new parse_setting("z", dr[setting.column_headers[i]].ToString()); new_row_values[i] = p.parse_result; break; } } else { new_row_values[i] = dr[setting.column_headers[i]].ToString(); } } DataGridViewRow row = new DataGridViewRow(); row.CreateCells(dgv); row.SetValues(new_row_values); rows.Add(row); } dgv.Rows.AddRange(rows.ToArray()); } } foreach (DataGridViewRow check_row in dgv.Rows) { if (setting.color_check_header == "") break; if (check_row.Cells[setting.color_check_header].Value != null && check_row.Cells[setting.color_check_header].Value.ToString() != "") { DateTime result; DateTime.TryParse(check_row.Cells[setting.color_check_header].Value.ToString(), out result); int m = result.Month; switch (m) { case 1: check_row.DefaultCellStyle.BackColor = Color.Salmon; break; case 2: check_row.DefaultCellStyle.BackColor = Color.LemonChiffon; break; case 3: check_row.DefaultCellStyle.BackColor = Color.SpringGreen; break; case 4: check_row.DefaultCellStyle.BackColor = Color.PowderBlue; break; case 5: check_row.DefaultCellStyle.BackColor = Color.Thistle; break; case 6: check_row.DefaultCellStyle.BackColor = Color.BurlyWood; break; case 7: check_row.DefaultCellStyle.BackColor = Color.HotPink; break; case 8: check_row.DefaultCellStyle.BackColor = Color.DarkSeaGreen; break; case 9: check_row.DefaultCellStyle.BackColor = Color.DeepSkyBlue; break; case 10: check_row.DefaultCellStyle.BackColor = Color.DarkSlateBlue; break; case 11: check_row.DefaultCellStyle.BackColor = Color.DarkOrange; break; case 12: check_row.DefaultCellStyle.BackColor = Color.Olive; break; } } } } catch (Exception e) { MessageBox.Show(e.Message); } } public void delete_dgv_row(string id) { try { using (OleDbConnection con = new OleDbConnection(setting.connection_string)) { con.Open(); OleDbCommand cmd = new OleDbCommand("delete from " + setting.main_table_name + " where id = " + id, con); cmd.ExecuteNonQuery(); } } catch (Exception e) { MessageBox.Show(e.Message); } } } public partial class dgv_setting { DataGridView dgv; setting setting; string form_type; public dgv_setting(DataGridView d, setting s, string f) { dgv = d; setting = s; form_type = f; } public void error_handle() { dgv.DataError += new DataGridViewDataErrorEventHandler((object sender, DataGridViewDataErrorEventArgs e)=> { e.Cancel = false; }); } public void hide_columns() { foreach (string c in setting.hide_headers) { dgv.Columns[c].Visible = false; } } public void read_only_columns() { foreach (string c in setting.read_only_headers) { dgv.Columns[c].ReadOnly = true; } } public void create_columns() { foreach (string s in setting.column_headers) { DataGridViewTextBoxColumn dgv_tbc = new DataGridViewTextBoxColumn(); dgv_tbc.Name = s; dgv_tbc.HeaderText = s; dgv_tbc.Width = 100; foreach (var w in setting.width_list) { int result; int.TryParse(w[2].ToString(), out result); if (w[0] == setting.main_form_instance.Text && w[1] == s) dgv_tbc.Width = result; } System.Diagnostics.Debug.Print(setting.main_form_instance.Text); if (setting.variable_type_dic.ContainsKey(s)) { parse_setting p; switch (setting.variable_type_dic[s]) { case "d": p = new parse_setting("d", ""); dgv_tbc.ValueType = p.parse_type; dgv_tbc.DefaultCellStyle.Format = p.parse_format_string; break; case "m": p = new parse_setting("m", ""); dgv_tbc.ValueType = p.parse_type; dgv_tbc.DefaultCellStyle.Format = p.parse_format_string; break; case "z": p = new parse_setting("z", ""); dgv_tbc.ValueType = p.parse_type; dgv_tbc.DefaultCellStyle.Format = p.parse_format_string; break; } } dgv.Columns.Add(dgv_tbc); } } public void change_flg_event() { dgv.CellValueChanged += new DataGridViewCellEventHandler((object sender, DataGridViewCellEventArgs e) => { dgv.Rows[e.RowIndex].Cells[setting.change_flg_header].Value = "1"; dgv.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Blue; }); } public void set_forcus_event() { if (form_type == "main") { dgv.CellValueChanged += new DataGridViewCellEventHandler((object sender, DataGridViewCellEventArgs e) => { int c1 = dgv.Columns["数量"].Index; int c2 = dgv.Columns["重量"].Index; int c3 = dgv.Columns["レート"].Index; int c4 = dgv.Columns["単価"].Index; int c5 = dgv.Columns["金額"].Index; if (e.ColumnIndex != c1 && e.ColumnIndex != c2 && e.ColumnIndex != c3 && e.ColumnIndex != c4) return; if (dgv.Rows[e.RowIndex].Cells[c4].Value == null || dgv.Rows[e.RowIndex].Cells[c4].Value.ToString() == "") return; if (dgv.Rows[e.RowIndex].Cells[c2].Value != null && dgv.Rows[e.RowIndex].Cells[c2].Value.ToString() != "" && dgv.Rows[e.RowIndex].Cells[c2].Value.ToString() != "0") { dgv.Rows[e.RowIndex].Cells[c5].Value = (decimal.Parse(dgv.Rows[e.RowIndex].Cells[c4].Value.ToString()) * decimal.Parse(dgv.Rows[e.RowIndex].Cells[c2].Value.ToString())).ToString(); } else if (dgv.Rows[e.RowIndex].Cells[c1].Value != null && dgv.Rows[e.RowIndex].Cells[c1].Value.ToString() != "") { dgv.Rows[e.RowIndex].Cells[c5].Value = (decimal.Parse(dgv.Rows[e.RowIndex].Cells[c1].Value.ToString()) * decimal.Parse(dgv.Rows[e.RowIndex].Cells[c4].Value.ToString())).ToString(); } else { dgv.Rows[e.RowIndex].Cells[c5].Value = ""; } if (dgv.Rows[e.RowIndex].Cells[c3].Value != null && dgv.Rows[e.RowIndex].Cells[c3].Value.ToString() != "" && dgv.Rows[e.RowIndex].Cells[c3].Value.ToString() != "0" && dgv.Rows[e.RowIndex].Cells[c5].Value != null && dgv.Rows[e.RowIndex].Cells[c5].Value.ToString() != "") { dgv.Rows[e.RowIndex].Cells[c5].Value = decimal.Parse(dgv.Rows[e.RowIndex].Cells[c5].Value.ToString()) * decimal.Parse(dgv.Rows[e.RowIndex].Cells[c3].Value.ToString()); } }); } if (form_type == "parts_sub") { dgv.CellValueChanged += new DataGridViewCellEventHandler((object sender, DataGridViewCellEventArgs e) => { int c1 = dgv.Columns["数量"].Index; int c2 = dgv.Columns["台数"].Index; int c3 = dgv.Columns["発注数量"].Index; if (e.ColumnIndex != c1 && e.ColumnIndex != c2) return; if (dgv.Rows[e.RowIndex].Cells[c1].Value == null || dgv.Rows[e.RowIndex].Cells[c1].Value.ToString() == "") return; if (dgv.Rows[e.RowIndex].Cells[c2].Value == null || dgv.Rows[e.RowIndex].Cells[c2].Value.ToString() == "") return; dgv.Rows[e.RowIndex].Cells[c3].Value = (decimal.Parse(dgv.Rows[e.RowIndex].Cells[c1].Value.ToString()) * decimal.Parse(dgv.Rows[e.RowIndex].Cells[c2].Value.ToString())).ToString(); }); } } public void set_click_supplier_master_event() { if (form_type == "main" || form_type == "parts" || form_type == "parts_sub") { foreach (string target_column in setting.supplier_master_header) { dgv.MouseClick += new MouseEventHandler((object sender, MouseEventArgs e) => { int c = dgv.HitTest(e.X, e.Y).ColumnIndex; int r = dgv.HitTest(e.X, e.Y).RowIndex; if (e.Button == MouseButtons.Right || c < 0 || r < 0) return; if (target_column != dgv.Columns[c].HeaderText) return; master_dialog f = new master_dialog(target_column, new ComboBox(), setting); f.StartPosition = FormStartPosition.Manual; f.Location = new Point(Cursor.Position.X, Cursor.Position.Y); f.ShowDialog(); if (f.clicked_enter) { foreach (DataGridViewCell cell in dgv.SelectedCells) { if (cell.OwningColumn.HeaderText == target_column) { cell.Value = f.inputted_value; dgv.Rows[cell.RowIndex].Cells["仕入先コード"].Value = f.inputted_cd; } } } }); } } } public void basic_properties() { dgv.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left; dgv.ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.False; dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None; dgv.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None; dgv.Font = new Font("MS UI Gothic", 12); dgv.RowTemplate.Height = 20; dgv.AllowUserToAddRows = false; typeof(DataGridView). GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic). SetValue(dgv, true, null); } } public class parse_setting { public Type parse_type = typeof(String); public string parse_format_string = ""; public string parse_result = null; public parse_setting(string type, string value) { try { switch (type) { case "d": parse_type = typeof(DateTime); parse_format_string = "yyyy-MM-dd"; if (value != "") parse_result = DateTime.Parse(value).ToString(parse_format_string); break; case "m": parse_type = typeof(Decimal); parse_format_string = "#,0"; if (value != "") parse_result = decimal.Parse(value).ToString(parse_format_string); break; case "n": parse_type = typeof(Decimal); parse_format_string = "#,0.0"; if (value != "") parse_result = decimal.Parse(value).ToString(parse_format_string); break; } } catch { parse_type = typeof(String); parse_format_string = ""; parse_result = null; } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class dgv_setting { public void set_click_context_event() { dgv.MouseClick += new MouseEventHandler((object sender, MouseEventArgs e) => { int c = dgv.HitTest(e.X, e.Y).ColumnIndex; int r = dgv.HitTest(e.X, e.Y).RowIndex; if (e.Button == MouseButtons.Left || c < 0 || r < 0) return; ContextMenu menu = new ContextMenu(); if (form_type == "main" || form_type == "parts" || form_type == "parts_sub" || form_type == "supply" || form_type == "size") { menu.MenuItems.Add("同一内容を入力(選択セル)", new EventHandler((object item_sender, EventArgs items_e) => { master_dialog f = new master_dialog("入力内容", new TextBox(), setting); f.StartPosition = FormStartPosition.Manual; f.Location = new Point(Cursor.Position.X, Cursor.Position.Y); f.ShowDialog(); if (f.clicked_enter) { foreach (DataGridViewCell cell in dgv.SelectedCells) { try { if (setting.variable_type_dic.ContainsKey(cell.OwningColumn.HeaderText)) { switch (setting.variable_type_dic[cell.OwningColumn.HeaderText]) { case "d": cell.Value = new parse_setting("d", f.inputted_value).parse_result; break; case "m": cell.Value = new parse_setting("m", f.inputted_value).parse_result; break; case "z": cell.Value = new parse_setting("z", f.inputted_value).parse_result; break; } } else { if (Array.IndexOf(setting.read_only_headers, cell.OwningColumn.HeaderText) == -1) { cell.Value = f.inputted_value; } } } catch { cell.Value = null; } } } })); } if (form_type == "parts") { menu.MenuItems.Add("材料手配テーブルへ転送(選択行)", new EventHandler((object item_sender, EventArgs items_e) => { DataGridView parent_dgv = ((DataGridView)setting.main_form_instance.parent_form.Controls["グリッドビュー"]); if (parent_dgv == null) return; var selected_rows_index = dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.RowIndex).Distinct(); foreach (int selected_row_index in selected_rows_index) { var new_row = new DataGridViewRow(); new_row.CreateCells(parent_dgv); new_row.Height = parent_dgv.RowTemplate.Height; for (int i = 0; i < setting.parts_sub_correspond.GetLength(0); i++) { string parts_cell_value = ""; if (dgv.Rows[selected_row_index].Cells[setting.parts_sub_correspond[i, 1]].Value != null) parts_cell_value = dgv.Rows[selected_row_index].Cells[setting.parts_sub_correspond[i, 1]].Value.ToString(); int parent_column_index = parent_dgv.Columns[setting.parts_sub_correspond[i, 0]].Index; if (new_row.Cells[parent_column_index].Value != null && new_row.Cells[parent_column_index].Value.ToString() != "") { new_row.Cells[parent_column_index].Value = new_row.Cells[parent_column_index].Value.ToString() + " " + parts_cell_value; } else { new_row.Cells[parent_column_index].Value = parts_cell_value; } } setting.main_form_instance.parent_form.Activate(); parent_dgv.Rows.Add(new_row); new_row.Cells[parent_dgv.Columns[setting.change_flg_header].Index].Value = "1"; } })); } if (form_type == "copy" || form_type == "parts_sub") { menu.MenuItems.Add("仕入台帳へ転送(選択行)", new EventHandler((object item_sender, EventArgs items_e) => { var selected_rows_index = dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.RowIndex).Distinct(); DataGridView parent_dgv = ((DataGridView)setting.main_form_instance.parent_form.Controls["グリッドビュー"]); for (int i = 0; i < parent_dgv.Rows.Count; i++) { if (parent_dgv.Rows[i].Cells[setting.id_header].Value != null && parent_dgv.Rows[i].Cells[setting.id_header].Value.ToString() != "") parent_dgv.Rows.Clear(); } foreach (int selected_row_index in selected_rows_index) { var new_row = new DataGridViewRow(); new_row.CreateCells(parent_dgv); new_row.Height = parent_dgv.RowTemplate.Height; if (setting.main_form_instance.form_type == "parts_sub") { for (int i = 0; i < setting.main_parts_correspond.GetLength(0); i++) { string parts_cell_value = ""; if (dgv.Rows[selected_row_index].Cells[setting.main_parts_correspond[i, 1]].Value != null) parts_cell_value = dgv.Rows[selected_row_index].Cells[setting.main_parts_correspond[i, 1]].Value.ToString(); int parent_column_index = parent_dgv.Columns[setting.main_parts_correspond[i, 0]].Index; if (new_row.Cells[parent_column_index].Value != null && new_row.Cells[parent_column_index].Value.ToString() != "") { new_row.Cells[parent_column_index].Value = new_row.Cells[parent_column_index].Value.ToString() + " " + parts_cell_value; } else { new_row.Cells[parent_column_index].Value = parts_cell_value; } } } else if(setting.main_form_instance.form_type == "copy") { for (int i = 0; i < setting.column_headers.Length; i++) { string column_name = setting.column_headers[i]; if(column_name != setting.id_header && column_name != setting.change_flg_header) { string copy_cell_value = ""; if (dgv.Rows[selected_row_index].Cells[column_name].Value != null) copy_cell_value = dgv.Rows[selected_row_index].Cells[column_name].Value.ToString(); int parent_column_index = parent_dgv.Columns[column_name].Index; new_row.Cells[parent_column_index].Value = copy_cell_value; } } } setting.main_form_instance.parent_form.Activate(); parent_dgv.Rows.Add(new_row); new_row.Cells[parent_dgv.Columns[setting.change_flg_header].Index].Value = "1"; } })); } if (form_type == "main") { menu.MenuItems.Add("注文書作成(選択行)", new EventHandler((object item_sender, EventArgs items_e) => { create_excel excel = new create_excel(); excel.create_order_work(dgv, setting,1); })); } if (form_type == "parts_sub") { menu.MenuItems.Add("作業指示書作成(選択行)", new EventHandler((object item_sender, EventArgs items_e) => { create_excel excel = new create_excel(); excel.create_order_work(dgv, setting,2); })); } if (form_type == "main" || form_type == "parts" || form_type == "parts_sub" || form_type == "supply" || form_type == "size") { menu.MenuItems.Add("-"); menu.MenuItems.Add("削除(選択行)", new EventHandler((object items_sender, EventArgs items_e) => { DialogResult result = MessageBox.Show("本当に削除しますか?", "", MessageBoxButtons.YesNo); if (result == DialogResult.No) return; db_setting db = new db_setting(setting); var selected_rows_index = dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.RowIndex).Distinct(); foreach (int selected_row_index in selected_rows_index) { if (dgv.Rows[selected_row_index].Cells[setting.id_header].Value != null) { string id = dgv.Rows[selected_row_index].Cells[setting.id_header].Value.ToString(); db.delete_dgv_row(id); } } var selected_rows = dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.OwningRow).Distinct(); foreach (DataGridViewRow selected_row in selected_rows) { dgv.Rows.Remove(selected_row); } })); } menu.Show(dgv, new Point(e.X, e.Y)); }); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; namespace WindowsFormsApp1 { public partial class main_form { private void set_button_event() { if (form_type == "main" || form_type == "copy" || form_type == "parts" || form_type == "supply") { ((Button)this.Controls["検索"]).Click += new EventHandler((object sender, EventArgs e) => { dgv_load(); }); } if (form_type == "main" || form_type == "copy" || form_type == "parts" || form_type == "supply") { ((Button)this.Controls["クリア"]).Click += new EventHandler((object sender, EventArgs e) => { foreach (Control c in this.Controls) { if (c.GetType() == typeof(TextBox) || c.GetType() == typeof(ComboBox)) { c.Text = ""; c.BackColor = SystemColors.Window; } if (c.Name == "表示種類") c.Text = "全部"; if (c.Name == "一致種類") c.Text = "曖昧"; } dgv_load(); }); } if (form_type == "main") { ((Button)this.Controls["材料手配"]).Click += new EventHandler((object sender, EventArgs e) => { main_form f_sub = new main_form("parts_sub", this); main_form f = new main_form("parts", f_sub); f_sub.Shown += new EventHandler((object shown_sender, EventArgs shown_e) => { f_sub.Left = f.Left + 100; f_sub.Top = f.Top + 100; }); f_sub.Show(); f.Show(); }); } if (form_type == "main") { ((Button)this.Controls["複製"]).Click += new EventHandler((object sender, EventArgs e) => { main_form f = new main_form("copy", this); f.Show(); }); } if (form_type == "main" || form_type == "parts" || form_type == "parts_sub" || form_type == "supply" || form_type == "size") { ((Button)this.Controls["新規"]).Click += new EventHandler((object sender, EventArgs e) => { dgv_new_row(); }); } if (form_type == "main") { ((Button)this.Controls["集計表示"]).Click += new EventHandler((object sender, EventArgs e) => { main_form f = new main_form("sumup", this); f.ShowDialog(); }); } if (form_type == "main" || form_type == "parts" || form_type == "supply" || form_type == "sumup") { ((Button)this.Controls["エクセルで表示"]).Click += new EventHandler((object sender, EventArgs e) => { var excel = new create_excel(); excel.dgv_copy(((DataGridView)this.Controls["グリッドビュー"]),setting); }); } if (form_type == "main" || form_type == "parts" || form_type == "supply" || form_type == "size") { ((Button)this.Controls["データベースに反映"]).Click += new EventHandler((object sender, EventArgs e) => { DataGridView dgv = (DataGridView)this.Controls["グリッドビュー"]; int r = dgv.CurrentCell.RowIndex; int c = dgv.CurrentCell.ColumnIndex; Boolean isNewRowAdded = false; for (int i = 0; i < dgv.Rows.Count; i++) { if (dgv.Rows[i].Cells[setting.id_header].Value == null) isNewRowAdded = true; } int pre_count = dgv.Rows.Count; db_setting db = new db_setting(setting); db.insert_update_dgv(dgv); int post_count = dgv.Rows.Count; if (isNewRowAdded) { dgv.FirstDisplayedScrollingRowIndex = dgv.Rows.Count - 1; } else { if (pre_count == post_count) dgv.CurrentCell = dgv.Rows[r].Cells[c]; } }); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
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.Windows.Forms; namespace WindowsFormsApp1 { public partial class master_dialog : Form { public List<string[]> cd_name_list; public string inputted_value = ""; public string inputted_cd = ""; public Boolean clicked_enter = false; public master_dialog(string target_column_name, Control control_type, setting setting) { InitializeComponent(); Text = target_column_name; Control control = control_type; control.Location = new Point(12, 12); control.Font = new Font("MS UI Gothic", 12); control.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right; control.Width = this.Width - 40; this.Controls.Add(control); if (control_type.GetType() == typeof(ComboBox)) { db_setting db = new db_setting(setting); cd_name_list = db.get_master_list2(target_column_name, setting.supplier_table_name); var name_list = cd_name_list.Select(x => x[1]).ToArray(); ((ComboBox)control).Items.AddRange(name_list.ToArray()); ((ComboBox)control).AutoCompleteMode = AutoCompleteMode.Append; ((ComboBox)control).AutoCompleteSource = AutoCompleteSource.ListItems; } control.KeyDown += new KeyEventHandler((object sender, KeyEventArgs e)=> { if (e.KeyCode == Keys.Enter) { inputted_value = control.Text; if (control_type.GetType() == typeof(ComboBox) && inputted_value != "") { foreach (var c in cd_name_list) { if (c[1] == inputted_value) inputted_cd = c[0]; } } clicked_enter = true; this.Close(); } if (e.KeyCode == Keys.Escape) { this.Close(); } }); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; namespace WindowsFormsApp1 { class create_excel { public void create_order_work(DataGridView dgv, setting setting, int t) { if (Type.GetTypeFromProgID("Excel.Application") == null) return; string book_name = ""; switch (t) { case 1: book_name = @"\create_order.xlsm"; break; case 2: book_name = @"\create_work.xlsm"; break; } SaveFileDialog sfd = new SaveFileDialog(); sfd.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); sfd.Filter = "xlsm | *.xlsm"; if (sfd.ShowDialog() != DialogResult.OK) return; var ex = new Microsoft.Office.Interop.Excel.Application(); ex.Visible = false; ex.DisplayAlerts = false; var bs = ex.Workbooks; var wb = bs.Open(System.Windows.Forms.Application.StartupPath + book_name); var ss = wb.Sheets; var ws = ss["data"]; try { wb.SaveCopyAs(sfd.FileName); } catch(Exception e) { MessageBox.Show(e.Message); return; } finally { wb.Close(); Marshal.ReleaseComObject(ws); ws = null; Marshal.ReleaseComObject(ss); ss = null; Marshal.ReleaseComObject(wb); wb = null; Marshal.ReleaseComObject(bs); bs = null; Marshal.ReleaseComObject(ex); ex = null; } ex = new Microsoft.Office.Interop.Excel.Application(); bs = ex.Workbooks; wb = bs.Open(sfd.FileName); ss = wb.Sheets; ws = ss["data"]; var selected_rows_index = dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.RowIndex).Distinct(); if(t == 1) { int start_row = 1; foreach (int selected_row_index in selected_rows_index) { var rc = ws.Cells[start_row, 1]; if (dgv.Rows[selected_row_index].Cells["仕入先"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["仕入先"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 2]; if (dgv.Rows[selected_row_index].Cells["品名"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["品名"].Value.ToString(); if (dgv.Rows[selected_row_index].Cells["材質"].Value != null) rc.value = rc.value + " " + dgv.Rows[selected_row_index].Cells["材質"].Value.ToString(); if (dgv.Rows[selected_row_index].Cells["型番・サイズ"].Value != null) rc.value = rc.value + " " + dgv.Rows[selected_row_index].Cells["型番・サイズ"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 3]; if (dgv.Rows[selected_row_index].Cells["発注数量"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["発注数量"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 4]; if (dgv.Rows[selected_row_index].Cells["納期"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["納期"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 5]; if (dgv.Rows[selected_row_index].Cells["型式"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["型式"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 6]; if (dgv.Rows[selected_row_index].Cells["納品先"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["納品先"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 7]; rc.value = start_row.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; start_row++; } } if(t == 2) { int start_row = 1; foreach (int selected_row_index in selected_rows_index) { var rc = ws.Cells[start_row, 1]; if (dgv.Rows[selected_row_index].Cells["型式"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["型式"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 2]; if (dgv.Rows[selected_row_index].Cells["品名"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["品名"].Value.ToString(); if (dgv.Rows[selected_row_index].Cells["材質"].Value != null) rc.value = rc.value + " " + dgv.Rows[selected_row_index].Cells["材質"].Value.ToString(); if (dgv.Rows[selected_row_index].Cells["寸法"].Value != null) rc.value = rc.value + " " + dgv.Rows[selected_row_index].Cells["寸法"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 3]; if (dgv.Rows[selected_row_index].Cells["台数"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["台数"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 4]; if (dgv.Rows[selected_row_index].Cells["発注数量"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["発注数量"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 5]; if (dgv.Rows[selected_row_index].Cells["班名"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["班名"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 6]; if (dgv.Rows[selected_row_index].Cells["納期"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["納期"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = ws.Cells[start_row, 7]; rc.value = "番号"; System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; start_row++; } } try { if (t == 1) ex.Run("create_order"); if (t == 2) ex.Run("auto_open"); ex.Visible = true; ex.DisplayAlerts = true; } catch { MessageBox.Show("エクセルファイルの作成に失敗しました。"); } finally { Marshal.ReleaseComObject(ws); ws = null; Marshal.ReleaseComObject(ss); ss = null; Marshal.ReleaseComObject(wb); wb = null; Marshal.ReleaseComObject(bs); bs = null; Marshal.ReleaseComObject(ex); ex = null; } } public void dgv_copy(DataGridView dgv,setting setting) { if (Type.GetTypeFromProgID("Excel.Application") == null) return; SaveFileDialog sfd = new SaveFileDialog(); sfd.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); sfd.Filter = "xlsm | *.xlsm"; if (sfd.ShowDialog() != DialogResult.OK) return; var ex = new Microsoft.Office.Interop.Excel.Application(); ex.Visible = false; ex.DisplayAlerts = false; var bs = ex.Workbooks; var wb = bs.Open(System.Windows.Forms.Application.StartupPath + @"\dgv_copy.xlsm"); var ss = wb.Sheets; var ws = ss["1"]; try { wb.SaveCopyAs(sfd.FileName); } catch (Exception e) { MessageBox.Show(e.Message); return; } finally { wb.Close(); Marshal.ReleaseComObject(ws); ws = null; Marshal.ReleaseComObject(ss); ss = null; Marshal.ReleaseComObject(wb); wb = null; Marshal.ReleaseComObject(bs); bs = null; Marshal.ReleaseComObject(ex); ex = null; } ex = new Microsoft.Office.Interop.Excel.Application(); bs = ex.Workbooks; wb = bs.Open(sfd.FileName); ss = wb.Sheets; ws = ss["1"]; try { if (setting.main_form_instance.form_type == "sumup") { ex.Run("dgv_copy", setting.main_form_instance.build_query_sumup(), setting.connection_string); } else { ex.Run("dgv_copy", setting.main_form_instance.build_query(), setting.connection_string); } ex.Visible = true; ex.DisplayAlerts = true; } catch { MessageBox.Show("エクセルファイルの作成に失敗しました。"); } finally { Marshal.ReleaseComObject(ws); ws = null; Marshal.ReleaseComObject(ss); ss = null; Marshal.ReleaseComObject(wb); wb = null; Marshal.ReleaseComObject(bs); bs = null; Marshal.ReleaseComObject(ex); ex = null; } } } } |
C# CD等一覧の一括リネーム
大量のリネームがあったのでamazon等からテキストデータを持ってきて利用した。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
using System; using System.Windows.Forms; namespace cd_ren { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void listBox1_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } } private void button3_Click(object sender, EventArgs e) { int i = listBox1.SelectedIndex; if (i <= 0) return; var o = listBox1.SelectedItem; listBox1.Items.RemoveAt(i); listBox1.Items.Insert(i - 1, o); listBox1.SelectedIndex = i - 1; } private void button1_Click(object sender, EventArgs e) { int i = listBox1.SelectedIndex; if (listBox1.Items.Count - 1 == i) return; var o = listBox1.SelectedItem; listBox1.Items.RemoveAt(i); listBox1.Items.Insert(i + 1, o); listBox1.SelectedIndex = i + 1; } private void listBox1_DragDrop(object sender, DragEventArgs e) { string[] file_names = (string[])e.Data.GetData(DataFormats.FileDrop, false); listBox1.Items.AddRange(file_names); } private void button2_Click(object sender, EventArgs e) { for(int r = 0; r < listBox1.Items.Count; r++ ) { if (textBox1.Lines.Length - 1 < r || textBox1.Lines[r] == "") return; var original_full_path = listBox1.Items[r].ToString(); var new_full_path = System.IO.Path.GetDirectoryName(listBox1.Items[r].ToString()) + @"\" + textBox1.Lines[r].ToString() + ".mp3"; System.IO.File.Copy(original_full_path, new_full_path); } } } } |
C# 即席学習タイマー
ソフトの起動で計測を開始、終了で停止するだけの単純なタイマー。自分のモチベーションアップ用。
時間のリセットはdat.xmlを削除。Cドライブなどで実行すると落ちる。
以前も似たようなソフトを作ろうとしていたが、面倒になったのでシンプルにした。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
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.Windows.Forms; namespace study_timer_simple { public partial class Form1 : Form { public Form1() { InitializeComponent(); string path = Application.StartupPath + @"\dat.xml"; TimeSpan load_time_span = new TimeSpan(); if (System.IO.File.Exists(path)) { System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(int[])); System.IO.StreamReader sr = new System.IO.StreamReader(path, new UTF8Encoding(false)); int[] ts = (int[])x.Deserialize(sr); load_time_span = new TimeSpan(ts[0], ts[1], ts[2], ts[3]); sr.Close(); } TimeSpan current_time_span = new TimeSpan(); DateTime original_dt = DateTime.Now; Timer t = new Timer(); t.Tick += new EventHandler((object t_sender, EventArgs t_e) => { current_time_span = (DateTime.Now - original_dt); int h = (load_time_span + current_time_span).Days * 24 + (load_time_span + current_time_span).Hours; label1.Text = h.ToString() + "時間" + (load_time_span + current_time_span).ToString(@"mm\分ss\秒"); }); t.Start(); this.FormClosed += new FormClosedEventHandler((object sender, FormClosedEventArgs e) => { System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(int[])); System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, new UTF8Encoding(false)); x.Serialize(sw, new int[] { (int)(load_time_span + current_time_span).Days, (int)(load_time_span + current_time_span).Hours, (int)(load_time_span + current_time_span).Minutes, (int)(load_time_span + current_time_span).Seconds }); sw.Close(); }); } } } |
C# Excel操作②
この書き方だと落ちた時にプロセスが残る。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; namespace WindowsFormsApp1 { class create_excel { public void create_order(DataGridView dgv, setting setting) { var ex = new Microsoft.Office.Interop.Excel.Application(); ex.Visible = true; ex.DisplayAlerts = false; var wbs = ex.Workbooks; var wb = wbs.Open(System.Windows.Forms.Application.StartupPath + @"\po.xlsx"); var wss = wb.Sheets; var ws = wss["po"]; var _wbs = ex.Workbooks; var _wb = _wbs.Add(); var _wss = _wb.Sheets; var _ws = _wss[1]; ws.copy(_ws); wb.Close(); var order = _wss["po"]; var selected_rows_index = dgv.SelectedCells.Cast<DataGridViewCell>().Select(x => x.RowIndex).Distinct(); int counter = 18; foreach (int selected_row_index in selected_rows_index) { if (counter == 29) { MessageBox.Show("選択行数が多いため一部表示されていません。"); break; } if (dgv.Rows[selected_row_index].Cells[setting.id_header].Value != null) { var rc = order.Cells[4, 1]; if (dgv.Rows[selected_row_index].Cells["仕入先"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["仕入先"].Value.ToString() + " 御中"; System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = order.Cells[counter, 1]; if(dgv.Rows[selected_row_index].Cells["品名"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["品名"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = order.Cells[counter, 2]; if(dgv.Rows[selected_row_index].Cells["発注数量"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["発注数量"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = order.Cells[counter, 3]; if(dgv.Rows[selected_row_index].Cells["納期"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["納期"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; rc = order.Cells[counter, 4]; if(dgv.Rows[selected_row_index].Cells["型式"].Value != null) rc.value = dgv.Rows[selected_row_index].Cells["型式"].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; counter++; } } Marshal.ReleaseComObject(order); order = null; Marshal.ReleaseComObject(_ws); _ws = null; Marshal.ReleaseComObject(_wss); _wss = null; Marshal.ReleaseComObject(_wb); _wb = null; Marshal.ReleaseComObject(_wbs); _wbs = null; Marshal.ReleaseComObject(ws); ws = null; Marshal.ReleaseComObject(wss); wss = null; Marshal.ReleaseComObject(wb); wb = null; Marshal.ReleaseComObject(wbs); wbs = null; Marshal.ReleaseComObject(ex); ex = null; } public void dgv_copy(DataGridView dgv) { var ex = new Microsoft.Office.Interop.Excel.Application(); ex.Visible = true; ex.DisplayAlerts = false; var wbs = ex.Workbooks; var wb = wbs.Add(); var wss = wb.Sheets; var ws = wss[1]; for (int r = 0; r < dgv.Rows.Count; r++) { for (int c = 0; c < dgv.Columns.Count; c++) { var rc = ws.Cells[r + 1, c + 1]; if (dgv.Rows[r].Cells[c].Value != null) rc.Value = dgv.Rows[r].Cells[c].Value.ToString(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rc); rc = null; } } Marshal.ReleaseComObject(ws); ws = null; Marshal.ReleaseComObject(wss); wss = null; Marshal.ReleaseComObject(wb); wb = null; Marshal.ReleaseComObject(wbs); wbs = null; Marshal.ReleaseComObject(ex); ex = null; } } } |
C# デスクトップに検索ボックス
昔、デスクトップに検索ボックスを表示するアプリがあった気がして、同じようなものを作りはじめてみたが、どうも使わなそうなので中止。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
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.Windows.Forms; namespace 検索ボックス { public partial class Form1 : Form { private Point mouse_point; public Form1() { InitializeComponent(); load_xml(); NotifyIcon ic = new NotifyIcon(); ic.Visible = true; ic.Icon = Icon; ic.MouseDoubleClick += new MouseEventHandler((object sender, MouseEventArgs e) => { this.Close(); }); this.ShowInTaskbar = false; this.FormBorderStyle = FormBorderStyle.None; this.TransparencyKey = this.BackColor; this.comboBox1.AutoCompleteMode = AutoCompleteMode.Append; this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems; this.comboBox1.MouseDown += new MouseEventHandler((object sender, MouseEventArgs e)=> { if(e.Button == MouseButtons.Left) { mouse_point = new Point(e.X, e.Y); } }); this.comboBox1.MouseMove += new MouseEventHandler((object sender, MouseEventArgs e)=> { if(e.Button == MouseButtons.Left) { this.Left += e.X - mouse_point.X; this.Top += e.Y - mouse_point.Y; } }); this.comboBox1.KeyDown += new KeyEventHandler((object sender, KeyEventArgs e) => { if(e.KeyCode == Keys.Enter) { string tmp = Uri.EscapeDataString(comboBox1.Text); System.Diagnostics.Process.Start(@"https://www.google.co.jp/search?q=" + tmp); comboBox1.Items.Add(comboBox1.Text); save_xml(); } }); } private void load_xml() { if (!System.IO.File.Exists(Application.StartupPath + @"\dat.xml")) return; System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(string[])); System.IO.StreamReader sr = new System.IO.StreamReader(Application.StartupPath + @"\dat.xml", new UTF8Encoding(false)); string[] items = (string[])xs.Deserialize(sr); comboBox1.Items.AddRange(items); sr.Close(); } private void save_xml() { System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(string[])); System.IO.StreamWriter sw = new System.IO.StreamWriter(Application.StartupPath + @"\dat.xml", false, new UTF8Encoding(false)); List<string> items = comboBox1.Items.Cast<string>().ToList(); xs.Serialize(sw, items.ToArray()); sw.Close(); } } } |
C# 承認テストプログラム
承認処理。ハッシュを使って見たけれど実用的ではなさそう。
Main.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
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.Windows.Forms; using System.Data.OleDb; using System.IO; namespace ファイル認証フォーム { public partial class Main : Form { public Main() { InitializeComponent(); this.Text = "ファイル認証フォーム 1.0"; create_dgv(); if (!load_dgv()) return; dataGridView1.CellDoubleClick += new DataGridViewCellEventHandler(onclick_dgv); } private void click_approval(string id, string approval_name) { string qry; string msg; if (approval_name != "") { DialogResult result = MessageBox.Show("既に認証済みです。認証を解除しますか?", "", MessageBoxButtons.YesNo); if (result == DialogResult.No) return; UserPassword f = new UserPassword(approval_name); f.ShowDialog(); if (!f.approval_check) return; qry = "update dat_tbl set approval_name = null where id = " + id + ";"; msg = "解除"; } else { UserPassword f = new UserPassword(); f.ShowDialog(); if (!f.approval_check) return; qry = "update dat_tbl set approval_name = '" + f.approval_user + "' where id = " + id + ";"; msg = "登録"; } using (OleDbConnection con = new OleDbConnection(UserStrings.ds_dat)) { try { con.Open(); } catch { MessageBox.Show("データーベース接続にエラーが発生しました。"); return; } OleDbCommand cmd = new OleDbCommand(qry, con); try { cmd.ExecuteNonQuery(); } catch { MessageBox.Show("正しく" + msg + "できませんでした。"); return; } MessageBox.Show(msg + "しました。"); load_dgv(); } } private void click_delete(string id, string approval_name, string file_name) { DialogResult result = MessageBox.Show(file_name + "\n" + "削除しますか?", "", MessageBoxButtons.YesNo); if (result == DialogResult.No) return; if (approval_name == "") { row_delete(id); } else { UserPassword f = new UserPassword(approval_name); f.ShowDialog(); if (!f.approval_check) { MessageBox.Show("承認者以外は削除できません。"); return; } row_delete(id); } } private void click_open(string id, string approval_name, string file_name, string file_path) { if (!File.Exists(file_path)) { MessageBox.Show("ファイルが存在しません。"); return; } string current_hash; using (FileStream fs = new FileStream(file_path, FileMode.Open, FileAccess.Read, FileShare.Read)) { System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bs = md5.ComputeHash(fs); md5.Clear(); StringBuilder res = new StringBuilder(); foreach (byte b in bs) { res.Append(b.ToString("x2")); } current_hash = res.ToString(); } using (OleDbConnection con = new OleDbConnection(UserStrings.ds_dat)) { try { con.Open(); } catch { MessageBox.Show("データーベース接続にエラーが発生しました。"); return; } try { string q = "select * from dat_tbl where id = " + id + ";"; OleDbCommand cmd = new OleDbCommand(q, con); using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { if (dr["md5"].ToString() == current_hash) { System.Diagnostics.Process.Start(Path.GetDirectoryName(file_path)); return; } } MessageBox.Show("ハッシュ値が一致しません。"); return; } } catch { MessageBox.Show("データ取得中にエラーが発生しました。"); } } } private void row_delete(string id) { using (OleDbConnection con = new OleDbConnection(UserStrings.ds_dat)) { try { con.Open(); } catch { MessageBox.Show("データーベース接続にエラーが発生しました。"); return; } string q = "delete from dat_tbl where id = " + id + ";"; OleDbCommand cmd = new OleDbCommand(q, con); try { cmd.ExecuteNonQuery(); } catch { MessageBox.Show("正しく削除できませんでした。"); return; } MessageBox.Show("削除しました。"); load_dgv(); } } private void onclick_dgv(object sender, DataGridViewCellEventArgs e) { int c = e.ColumnIndex; int r = e.RowIndex; string id = dataGridView1.Rows[r].Cells[0].Value.ToString(); string approval_name = dataGridView1.Rows[r].Cells[1].Value.ToString(); string file_name = dataGridView1.Rows[r].Cells[4].Value.ToString(); string file_path = dataGridView1.Rows[r].Cells[5].Value.ToString(); if (c == 1 && r >= 0) click_approval(id, approval_name); if (c == 4 && r >= 0) click_open(id, approval_name, file_name, file_path); if (c == 5 && r >= 0) click_delete(id, approval_name, file_name); } private void create_dgv() { string[] headers = new string[] { "", //0 "承認者 (承認)", "得意先", "種類", "ファイル名 (ファイルオープン)",//4 "パス名 (登録削除)",//5 "ハッシュ値", "更新日時" }; foreach (string h in headers) { DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn(); col.HeaderText = h; dataGridView1.Columns.Add(col); } dataGridView1.ReadOnly = true; dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.Columns[0].Visible = false; dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dataGridView1.ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.False; dataGridView1.Font = new Font("MS UI Gothic", 12); dataGridView1.RowTemplate.Height = 32; dataGridView1.AllowUserToAddRows = false; } public bool load_dgv(string q = "select * from dat_tbl order by updated;") { dataGridView1.Rows.Clear(); using (OleDbConnection con = new OleDbConnection(UserStrings.ds_dat)) { try { con.Open(); } catch { MessageBox.Show("データーベース接続にエラーが発生しました。"); return false; } try { OleDbCommand cmd = new OleDbCommand(q, con); using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { dataGridView1.Rows.Add( dr["id"].ToString(), dr["approval_name"].ToString(),//1 dr["customer"].ToString(), dr["document_type"].ToString(), dr["file_name"].ToString(),//4 dr["file_path"].ToString(),//5 dr["md5"].ToString(), dr["updated"].ToString() ); } } } catch { MessageBox.Show("データ取得中にエラーが発生しました。"); return false; } } return true; } private void Form1_DragEnter(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false); if (e.Data.GetDataPresent(DataFormats.FileDrop)) { foreach (string s in files) { if (!File.Exists(s)) return; } e.Effect = DragDropEffects.Copy; } } private void Form1_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop,false); PathSplit f = new PathSplit(files, this); f.ShowDialog(); } } } |
UserPassword.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
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.Windows.Forms; using System.Data.OleDb; namespace ファイル認証フォーム { public partial class UserPassword : Form { public bool approval_check; public string approval_user; public UserPassword(string entered_user = "") { InitializeComponent(); if (entered_user == "") { textBox1.Enabled = true; } else { textBox1.Enabled = false; textBox1.Text = entered_user; } } private void button1_Click(object sender, EventArgs e) { using (OleDbConnection con = new OleDbConnection(UserStrings.ds_approval)) { try { con.Open(); } catch { MessageBox.Show("データーベース接続にエラーが発生しました。"); approval_check = false; return; } string user_name = textBox1.Text.Replace("\'", "\'\'"); string password = textBox2.Text.Replace("\'", "\'\'"); try { string q = "select * from approval_tbl where user_name = '" + user_name + "';"; OleDbCommand cmd = new OleDbCommand(q, con); using (OleDbDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { if (dr["password"].ToString() == password) { approval_check = true; approval_user = user_name; this.Close(); return; } } MessageBox.Show("ユーザーが存在しません。"); approval_check = false; return; } } catch { MessageBox.Show("データ取得中にエラーが発生しました。"); approval_check = false; } } } } } |
UserStrings.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ファイル認証フォーム { class UserStrings { public static string ds_dat = "provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + @"\dat.mdb;"; public static string ds_approval = "provider=microsoft.jet.oledb.4.0;data source=" + Application.StartupPath + @"\approval.mdb;"; } } |
PathSplit.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
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.Windows.Forms; using System.Data.OleDb; using System.IO; namespace ファイル認証フォーム { public partial class PathSplit : Form { Main fm; public PathSplit(string[] files, Main f) { fm = f; InitializeComponent(); string[] path = files[0].Split('\\'); if (path.Length >= 1) comboBox3.Text = path[path.Length - 1]; if (path.Length >= 2) comboBox2.Text = path[path.Length - 2]; if (path.Length >= 3) comboBox1.Text = path[path.Length - 3]; comboBox1.Items.AddRange(path); comboBox2.Items.AddRange(path); comboBox3.Items.AddRange(path); textBox1.Text = files[0]; using (FileStream fs = new FileStream(files[0],FileMode.Open,FileAccess.Read,FileShare.Read)) { System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bs = md5.ComputeHash(fs); md5.Clear(); StringBuilder res = new StringBuilder(); foreach (byte b in bs) { res.Append(b.ToString("x2")); } textBox2.Text = res.ToString(); } } private bool duplicate_path_chechk() { using (OleDbConnection con = new OleDbConnection(UserStrings.ds_dat)) { try { con.Open(); } catch { MessageBox.Show("データーベース接続にエラーが発生しました。"); return false; } string file_path = textBox1.Text.Replace("\'", "\'\'"); try { string q = "select * from dat_tbl where file_path = '" + file_path + "';"; OleDbCommand cmd = new OleDbCommand(q, con); using (OleDbDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { MessageBox.Show("既に登録済です。パスは重複できません。"); return false; } else { return true; } } } catch { MessageBox.Show("データ取得にエラーが発生しました。"); return false; } } } private void button1_Click(object sender, EventArgs e) { if (!duplicate_path_chechk()) { this.Close(); return; } using (OleDbConnection con = new OleDbConnection(UserStrings.ds_dat)) { try { con.Open(); } catch { MessageBox.Show("データーベース接続にエラーが発生しました。"); return; } string customer = comboBox1.Text.Replace("\'", "\'\'"); string document_type = comboBox2.Text.Replace("\'", "\'\'"); string file_name = comboBox3.Text.Replace("\'", "\'\'"); string file_path = textBox1.Text.Replace("\'","\'\'"); string md5 = textBox2.Text; string notes = textBox3.Text.Replace("\'", "\'\'"); string q = "insert into dat_tbl (customer,document_type,file_name,file_path,md5,updated,notes)" + " values ('" + customer + "','" + document_type + "','" + file_name + "','" + file_path + "','" + md5 + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + notes + "');"; OleDbCommand cmd = new OleDbCommand(q,con); try { cmd.ExecuteNonQuery(); } catch { MessageBox.Show("正しく登録できませんでした。"); return; } MessageBox.Show("登録しました。"); this.Close(); fm.load_dgv(); } } } } |
C# クラスの実験
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); //動的な型=インスタンスの型。a.GetType() //静的な型=変数の型。typeof(a) //静的な型 / 動的な型 A a1 = new A(); B b1 = new B(); A a2 = new B(); MessageBox.Show(a1.GetType().ToString()); //A MessageBox.Show(b1.GetType().ToString()); //B MessageBox.Show(a2.GetType().ToString()); //B //a2はAの型の変数だけど、インスタンスはBが入っている。 MessageBox.Show(typeof(A).ToString()); //A MessageBox.Show(typeof(B).ToString()); //B //変数同士の代入時、静的な型で判断 //基底の変数に派生の変数を入れる=アップキャスト。(安全) //派生の変数に基底の変数を入れる=ダウンキャスト。(不可) //メソッドは通常静的な型で呼ばれる。 MessageBox.Show(a1.say()); //A MessageBox.Show(b1.say()); //B MessageBox.Show(a2.say()); //A //Virtualは動的な型でメソッドが呼ばれる。 //Virtualメソッドの再定義Override C c1 = new C(); D d1 = new D(); C c2 = new D(); MessageBox.Show(c1.say());//C MessageBox.Show(d1.say());//D MessageBox.Show(c2.say());//D //コンストラクタは、基底クラスが呼ばれ、派生クラスが呼ばれる。 } } public class A { public string say() { return "A"; } } public class B : A { public string say() { return "B"; } } public class C { public virtual string say() { return "C"; } } public class D : C { public override string say() { return "D"; } //virtualメソッドじゃないとoverrideできない。 } } |
C# Access(mdb) コード内で作成
コード内でmdb作成。Close入れないと接続が残っている。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System.Windows.Forms; //参照設定追加 //Microsoft ADO Ext X.X for DDL and Security //Microsoft ActiveX Data Objects 6.0 Library namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { ADOX.Catalog cat = new ADOX.Catalog(); ADODB.Connection db1 = cat.Create("Provider='Microsoft.Jet.OLEDB.4.0';Data Source=" + Application.StartupPath + @"\test1.mdb;Jet OLEDB:Engine Type=5"); ADODB.Connection db2 = cat.Create("Provider='Microsoft.Jet.OLEDB.4.0';Data Source=" + Application.StartupPath + @"\test2.mdb;Jet OLEDB:Engine Type=5"); db1.Close(); db2.Close(); } } } |
C# DataTable メモ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
using System.Data; using System.Linq; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); // データテーブル作成 DataTable dt = new DataTable("newTable"); // カラム作成 string[] cols = new string[] { "id", "name", "age" }; foreach (string c in cols) { dt.Columns.Add(c); } // データセット作成 DataSet ds = new DataSet(); // データセットにテーブルを追加 ds.Tables.Add(dt); // 値作成(2次元配列) string[,] vals = new string[,] { {"01", "02", "03", "04"}, // id {"aa", "bb", "cc", "dd"}, // name {"11", "12", "13", "14"} // age }; for (int r = 0; r < vals.GetLength(1); r++) // GetLength(0) = 3(1次元), GetLength(1) = 4(2次元) { DataRow row = ds.Tables["newTable"].NewRow(); // DataRow row = dt.NewRow(); このようにも書ける row["id"] = vals[0, r]; // [1次元、2次元] row["name"] = vals[1, r]; row["age"] = vals[2, r]; ds.Tables["newTable"].Rows.Add(row); } // データソース設定 dataGridView1.DataSource = ds.Tables["newTable"]; // 条件を追加したデータテーブル間での複写-------------------------------------------------------- var newTable = dt.Clone(); // ベースループ foreach (var baseRow in dt.AsEnumerable()) { // ①特定の行を飛ばす if (baseRow["id"].ToString() == "02") continue; // ②特定の文字列を置き換える if(baseRow["age"].ToString() == "13") { baseRow["age"] = "26"; } newTable.ImportRow(baseRow); } // データセット作成 DataSet ds2 = new DataSet(); // データセットにテーブルを追加 ds2.Tables.Add(newTable.Copy()); // データソース設定 dataGridView2.DataSource = ds2.Tables["newTable"]; } } } |