C#将Winform上的TextBox和ComBox的值导入和导出
一、将所有控件上的值导出到文件
1.使用递归遍历窗体上所有的TextBox和ComBox,将控件名称和控件的值存入List
实体类Result.cs
/// <summary>
/// 结果数据
/// </summary>
public class Result
{
/// <summary>
/// 文本框名称
/// </summary>
public string TextBoxName { get; set; }
/// <summary>
/// 文本框的值
/// </summary>
public string TextBoxValue { get; set; }
}
递归获取想要的控件
private void GetAllTextAndCombox(Control controls)
{
foreach (Control control in controls.Controls)
{
if (control is TextBox || control is ComboBox)
{
AllControls.Add(control);
}
if (control.Controls.Count > 0)
{
GetAllTextAndCombox(control);
}
}
}
获取控件的名称和值
List<Result> Results=new List<Result>();
for (int i = 0; i < AllControls.Count; i++)
{
Result result = new Result();
result.TextBoxName = AllControls[i].Name;
result.TextBoxValue = AllControls[i].Text;
Results.Add(result);
}
2.将实体序列化成字符串,保存字符串
if (Results.Count > 0)
{
string Resultstr = JsonConvert.SerializeObject(Results);
if (string.IsNullOrEmpty(Resultstr)) return;
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Title = "请选择保存文件路径";
saveFile.Filter = "数据文件(*.Single)|*.Single";
saveFile.OverwritePrompt = true; //是否覆盖当前文件
saveFile.RestoreDirectory = true; //还原目录
if (saveFile.ShowDialog() == DialogResult.OK)
{
if (!File.Exists(saveFile.FileName))
{
using (File.Create(saveFile.FileName)) { }
}
using (StreamWriter sw = new StreamWriter(saveFile.FileName, false))
{
sw.Write(Resultstr);
sw.Close();//写入
MessageBox.Show("已保存!");
}
}
}
二、从文件导入所有控件的值
读取文件内容,反序列化成实体,循环给控件赋值。
OpenFileDialog openFile = new OpenFileDialog();
openFile.Title = "请选择保存文件路径";
openFile.Filter = "数据文件(*.Single)|*.Single";
openFile.Multiselect = false;
if (openFile.ShowDialog() == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFile.FileName))
{
string Resultstr = sr.ReadToEnd();
if (string.IsNullOrEmpty(Resultstr)) return;
Results = JsonConvert.DeserializeObject<List<Result>>(Resultstr);
if (Results.Count <= 0) return;
for (int i = 0; i < Results.Count; i++)
{
Control ct = AllControls.Where(o => o.Name == Results[i].TextBoxName).FirstOrDefault();
if (ct != null)
{
ct.Text = Results[i].TextBoxValue;
}
}
sr.Close();
}
}

浙公网安备 33010602011771号