C# 将选中的项目从CheckedListBox选中的项目保存到.txt文件
我不熟悉c#和windows窗体应用程序。 我想保存以将选中的项目从checkedlistbox保存到一个.txt文件,如果不存在,则创建,如果存在,则追加 下面是我如何将数据绑定到checkedlistbox的,我不确定这是正确的方法,还是有其他方法向checkedboxlist添加值C# 将选中的项目从CheckedListBox选中的项目保存到.txt文件,c#,asp.net,C#,Asp.net,我不熟悉c#和windows窗体应用程序。 我想保存以将选中的项目从checkedlistbox保存到一个.txt文件,如果不存在,则创建,如果存在,则追加 下面是我如何将数据绑定到checkedlistbox的,我不确定这是正确的方法,还是有其他方法向checkedboxlist添加值 public void bind_clbDepartment() { DataSet ds = DataBank3.get_department(); DataTable
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
}
您可以尝试以下方法 使用在课程代码开头添加此
:
using System.IO;
并将此代码添加到要将选定复选框的值写入文件的位置:
string path = "<path to file>";
foreach (ListItem item in clbDepartment.CheckBoxes.Items)
if (item.Selected)
File.AppendAllText(path, item.Value);
字符串路径=”;
foreach(CLB部门中的ListItem项目。复选框。项目)
如果(选定项)
File.AppendAllText(路径,item.Value);
正如文章所说,您有一些选择
要将字符串数组写入文件,请执行以下操作
string[] lines = { "First line", "Second line", "Third line" };
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
{
file.WriteLine("Fourth line");
}
要编写单个字符串,请执行以下操作
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);
}
}
}
要在现有文件的末尾追加一行,请执行以下操作
string[] lines = { "First line", "Second line", "Third line" };
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
{
file.WriteLine("Fourth line");
}
您的问题是什么?我想将选中的值从我的checkedlistbox保存到一个.txt文件中