C# 如果文件存在,则自动选中复选框
我想创建一个程序,这样如果文件存在,复选框将自动检查C# 如果文件存在,则自动选中复选框,c#,winforms,C#,Winforms,我想创建一个程序,这样如果文件存在,复选框将自动检查 private void button3_Click(object sender, EventArgs e) { //check whether the file is exist or not if (string curFile = @"C:\s\test.txt") { } else { } } File.Exists(fileLocation)返回bool必须使用System.IO验证文件是否存在,然
private void button3_Click(object sender, EventArgs e)
{
//check whether the file is exist or not
if (string curFile = @"C:\s\test.txt")
{
}
else
{
}
}
File.Exists(fileLocation)
返回bool必须使用System.IO验证文件是否存在,然后将atributte.checked设置为true。大概是这样的:
if System.IO.File.Exists(@"C:\s\test.txt") {
yourcheckbox.checked = true
}
else {
yourcheckbox.checked = false
}
bool didItExist = File.Exists(@"c:\path\to\file.txt");
checkbox.Checked = didItExist;
由于File.Exists()
返回true
或false
,因此可以直接使用返回值:
yourcheckbox.Checked = File.Exists(@"c:\Path\To\File.txt");
这就相当于做这样的事情:
if System.IO.File.Exists(@"C:\s\test.txt") {
yourcheckbox.checked = true
}
else {
yourcheckbox.checked = false
}
bool didItExist = File.Exists(@"c:\path\to\file.txt");
checkbox.Checked = didItExist;
和/或这个
checkbox.Checked = File.Exists(@"c:\path\to\file.txt") ? true : false;
不要忘记使用System.IO添加代码>位于顶部,因为File.Exists()
从中派生
我认为第一个建议的替代方案是最简洁的方法
跟进你的评论。。。下面是一个功能完整的代码片段
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace AutoCheckCheckbxIfFileExist_45245562
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/*
* I'm adding the fields dynamically through code so that
* you know all the fields that are on my form.
* Because they are created dynamically, I'll use 'Find' later on
* to retrieve them.
*/
addButton();
addTextField();
addChkbx();
}
private void addChkbx()
{
/*
* This is the checkbox that will be dyamically checked or unchecked
*/
CheckBox chkbx = new CheckBox();
chkbx.Location = new Point(this.Location.X + 35, this.Location.Y + 55);
chkbx.Name = "thechkbx";
this.Controls.Add(chkbx);
}
private void addTextField()
{
/*
* This is the field I'll be looking at to pull the file path
*/
TextBox txtb = new TextBox();
txtb.Name = "txtbx_thebox";
txtb.Location = new Point(this.Location.X + 5, this.Location.X + 35);
this.Controls.Add(txtb);
}
private void addButton()
{
/*
* This will be the button you'll click on to get the check/uncheck behavior
*/
Button btn = new Button();
btn.Text = "ClickMe";
btn.Click += Btn_Click;
btn.Location = new Point(this.Location.X + 5, this.Location.Y + 5);
this.Controls.Add(btn);
}
private void Btn_Click(object sender, EventArgs e)
{
/*
* This is the answer to your question
* Because I dynamically create the fields, I'm using a Find to get them and use them.
*/
((CheckBox)this.Controls.Find("thechkbx", true)[0]).Checked = File.Exists(((TextBox)this.Controls.Find("txtbx_thebox", true)[0]).Text);
}
}
}
在代码顶部包括“Using System.IO”。之后:这一行是一个示例:checkBox1.Checked=File.Exists(@“c:\PathToFile\File.txt”)?true:false;checked=Checkedit不起作用,在我运行代码后,复选框仍然取消选中。