Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9749

C# Tips

$
0
0

クリップボードに保存

hoge.cs
publicvoidcrip(){//クリップボードに保存StringBuilderlstb_csv=newStringBuilder();for(intLL=0;LL<lsv_data.Items.Count;LL++){//2番目の項目から取得for(intCC=1;CC<lsv_data.Columns.Count-1;CC++){lstb_csv.Append(lsv_data.Items[LL].SubItems[CC].ToString());lstb_csv.Append("\t");}lstb_csv.Append("\r\n");}Clipboard.SetDataObject(lstb_csv.ToString(),false);}

カレントディレクトリ

hoge.cs
usingSystem.IO;stringpath=Directory.GetCurrentDirectory();

データベースから取得してコンボボックスに表示

hoge.cs
//コネクションオープンconnection.Open();using(vartransaction=connection.BeginTransaction()){using(SQLiteCommandcmd=connection.CreateCommand()){stringsql=$@"                               select yoku_id,yoku_pass from yoku_id                     ";try{cmd.CommandText=sql;using(SQLiteDataReaderdr=cmd.ExecuteReader()){while(dr.Read()){//コンボボックスにアイテムを追加するcb_yahooid.Items.Add(dr["yoku_id"].ToString());}//コンボボックスの表示設定cb_yahooid.SelectedIndex=0;}}catch(Exceptionex){MessageBox.Show("エラー発生!");return;}transaction.Commit();}}//コネクションクローズconnection.Close();

DBからDataGridViewへ

hoge.cs
#region現在のDBデータをdataGridViewへ読み込むprivatevoidNowdata_Read(){//コネクションオープンconnection.Open();//空のテーブルを作ります。//この時点では、DataGridViewと紐づいていません。this.datatable=newDataTable();//DataTableに読み込むデータをSQLで指定します。//今回はDataTableを指定していないので、SELECTで表示する列名が//のちのち紐づけを行った際のDataGridViewの列名になります。SQLiteDataAdapteradapter=newSQLiteDataAdapter("SELECT * FROM yoku_listdata;",connection);adapter.Fill(this.datatable);//データテーブルをDataGridViewに紐づけます。this.dataGridView1.DataSource=this.datatable;//データを読み込みます//this.DataRead();}#endregion

ボタンクリックして並列処理を実行する

スクレイピングなどの処理が長いプログラムを実行する場合は、BackgroudWorkerを使うのが一般的。

フォームにBackgroudWorkerを追加する
image.png

イベントを追加する
image.png

キャンセルを許可
image.png

hoge.cs
#regionデータ取得ボタンクリックprivatevoidbutton1_Click(objectsender,EventArgse){// BackgroundWorkerが処理中でないことを確認if(MainBackgroundWorker.IsBusy){MessageBox.Show("実行中です");return;}// 並列処理を開始する MainBackgroundWorker.RunWorkerAsync();}#endregion#region並列処理実行処理privatevoidOnDoWork(objectsender,System.ComponentModel.DoWorkEventArgse){//実行内容}#endregion#region並列処理終了処理privatevoidOnRunWorkerComleted(objectsender,System.ComponentModel.RunWorkerCompletedEventArgse){txt_status.Visible=false;MessageBox.Show("終了しました");}#endregion

参考:https://www.tetsuyanbo.net/tetsuyanblog/30437

並列処理(BackgroudWork)を中止する

事前にWorkerSupportsCancellation を true にしておく

hoge.cs
#regionstopボタンクリックprivatevoidbutton2_Click(objectsender,EventArgse){// BackgroundWorkerが処理中の時だけ実行if(MainBackgroundWorker.IsBusy){// 処理をキャンセルしますMainBackgroundWorker.CancelAsync();}}#endregion#region並列処理実行処理privatevoidOnDoWork(objectsender,System.ComponentModel.DoWorkEventArgse){for(inti=0;i<1000;i++){// ループ処理の途中にキャンセルされたかを確認するif(MainBackgroundWorker.CancellationPending){//キャンセルされてた場合の処理e.Cancel=true;return;}//実行処理}#endregion#region並列処理終了処理privatevoidOnRunWorkerComleted(objectsender,System.ComponentModel.RunWorkerCompletedEventArgse){if(e.Cancelled){MessageBox.Show("処理はキャンセルされました");}else{MessageBox.Show("処理完了");}txt_status.Visible=false;}#endregion

並列処理中にフォームを操作する

並列処理中にはフォームへのアクセスしようとするとエラーになります

hoge.cs
#region並列処理実行処理privatevoidOnDoWork(objectsender,System.ComponentModel.DoWorkEventArgse){// マルチスレット対応してテキストボックスを操作Invoke(newAction(status_close));// (引数あり)マルチスレット対応してテキストボックスを操作Invoke(newAction<string>(status_mess),"開始しました");}#endregionpublicvoidstatus_mess(stringmess){txt_status.Text=mess;}publicvoidstatus_close(){txt_status.Visible=false;}

メッセージボックス分岐

hoge.cs
DialogResultresult=MessageBox.Show("よろしいですか?","",MessageBoxButtons.YesNo);if(result==DialogResult.Yes){MessageBox.Show("かんたんC#");}

テキストファイル出力

hoge.cs
using(StreamWritersw=newStreamWriter(@"D:\test\hironimo.txt",false,Encoding.UTF8)){sw.WriteLine("おはよう");sw.WriteLine("こんにちは");sw.WriteLine("こんばんは");}

Viewing all articles
Browse latest Browse all 9749

Trending Articles