2017-06-07 21 views
0

私はC#とWindowsフォームアプリケーションが初めてです。 チェックリストボックスから選択したアイテムを.txtファイルに保存して保存したい場合は、保存したい場合は作成し、存在する場合は追加します。CheckedListBoxで選択された項目から選択した項目を.txtファイルに保存します。

ここで私はcheckedlistboxにデータをバインドしていますが、これが正しいかどうかわかりませんし、チェックボックスリストに値を追加する方法もあります。

public void bind_clbDepartment() 
    { 
     DataSet ds = DataBank3.get_department(); 
     DataTable dt = ds.Tables[0]; 

     foreach (DataRow drow in dt.Rows) 
     { 
      clbDepartment.Items.Add(drow["id_dept"] + ":" + drow["name_dept"]); 
     } 
    } 


private void Save_Click(object sender, EventArgs e) 
     { 
      //save selected items from clbDepartment to D:\test.txt 
      //create if not exist, append if exist 
     } 
+0

ご質問はありますか? –

+0

私のチェックリストボックスから選択した値を.txtファイルに保存したい – onigiri

答えて

0

をいくつかのオプションがあると言います

文字列をファイルに書き込むにはdo

string[] lines = { "First line", "Second line", "Third line" }; 
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines); 

配列の選択的な書き込み文字列にこの

string text = "A class is the most powerful data type in C#. Like a structure, a class defines the data and behavior of the data type."; 
System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text); 

を行う単一の文字列を書き込むには、既存のファイルの末尾に行を追加するには、この

using (System.IO.StreamWriter file = 
      new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt")) 
     { 
      foreach (string line in lines) 
      { 
       // If the line doesn't contain the word 'Second', write the line to the file. 
       if (!line.Contains("Second")) 
       { 
        file.WriteLine(line); 
       } 
      } 
     } 

を行い、この

を行います
using (System.IO.StreamWriter file = 
    new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true)) 
{ 
    file.WriteLine("Fourth line"); 
} 
0

以下を試すことができます。

あなたのクラスコードの先頭でこのusingを追加します。

using System.IO; 

そして、あなたがあなたのファイルに選択したチェックボックスの値を書きたい、このコードを追加しますthis記事として

string path = "<path to file>"; 

foreach (ListItem item in clbDepartment.CheckBoxes.Items) 
    if (item.Selected) 
     File.AppendAllText(path, item.Value); 
関連する問題