将复选框迭代为 pdf c# 类



所以我在之前的迭代中得到了一些很棒的帮助,效果很好!

我尝试使用以下信息修改我的代码 在 C# 中使用反射从字符串中获取属性值

但是要么我弄错了,要么我的类设置方式无法使用该方法。

我使用了代码

foreach (var checkbox in this.Controls.OfType<CheckBox>())
{
pdfFormFields.SetField(checkbox.Name, checkbox.Checked ? "Yes" : "No");
}

现在它工作得很好,我被告知使用一个类来使其更加统一我的班级是

public class Entries
{
///Some other Values
public string ColourW;
public bool CheckBox1 { get; set; }
public bool CheckBox2 { get; set; }
public bool CheckBox3 { get; set; }
public bool CheckBox4 { get; set; }
public bool CheckBox5 { get; set; }
public bool CheckBox6 { get; set; }
public bool CheckBox7 { get; set; }
public bool CheckBox8 { get; set; }
public bool CheckBox9 { get; set; }
}

我需要像上面这样的 foreach 语句,但要将信息设置为类中的数据,例如这样,但是我收到标识符预期错误。

foreach (var checkbox in this.Controls.OfType<CheckBox>())
{
Data.(checkbox.Name, checkbox.Checked ? "Yes" : "No");
}

非常感谢帮助,非常感谢帮助解释代码的工作原理!

提前对不起,我是一个硬件人!

编辑

因此解决了大部分问题,这要归功于 Kambay 设法将复选框放入和退出课堂@Furkan但由于某种原因,PDF 上的复选框不会设置为相同的状态?

更长的解释,类设置表单工作正常,调用时所有组合框和文本字段pdfFormFileds("Textx", Entries.ColourW);工作正常,但是使用代码时 PDF 复选框不会更改状态,我正在使用 iTextSharp 库

foreach (var box in Entries.CheckBoxes) 
{
pdfFormFields.SetField(box.Key, box.Value ? "Yes" : "No");
}

PDF 的设置

string pdfTemplate = @"C:Testing TemplatesPre V-Change Head Test Certificate Template.pdf";
string newFile = @"c:tempPDF" + Entries.SerialNumber + " " + Entries.TestedWithCal + " Pre V-Change Head Test Certificate.pdf";
string Created;
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;

将类编辑成这样:

public static class Entries
{
// ... all the other fields with static keyword
public static string ColourLRB;
public static string ColourW;
public static Dictionary<string, bool> CheckBoxes { get; } = new Dictionary<string, bool>(); // no set, so you can only modify this. 
}

然后:

foreach (var checkbox in this.Controls.OfType<CheckBox>())
{
CheckBoxes[checkbox.Name] = checkbox.Checked;
}

我认为您可以使用 LINQ 查询将复选框映射到键值对来改进 foreach 语句。如果你愿意,我可以编辑答案。

编辑,使用 LINQ 映射:(替换整个 foreach)

var boxes = this.Controls.OfType<CheckBox>();
CheckBoxes = boxes.ToDictionary(b => b.Name, b => b.Checked);

编辑2,再次设置

foreach(var box in Entries.CheckBoxes) // this is using static. For Singleton it would be "var box in Entries.Instance.CheckBoxes"
{
pdfFormFields.SetField(box.Key, box.Value ? "Yes" : "No");
}
var entries = new Entries(); // looks to me like this class and its members should be static, no?
foreach (var checkbox in this.Controls.OfType<CheckBox>())
{
if(checkbox.Name == "CheckBox1") entries.CheckBox1 = checkbox.Checked;
else if(checkbox.Name == "CheckBox2") entries.CheckBox2 = checkbox.Checked;
else if(checkbox.Name == "CheckBox3") entries.CheckBox3 = checkbox.Checked;
// ...
}

最新更新