Writing to a rich text box in c# - c#

New programmer here.
I've written an application to filter out password protected files from a large collection. It is working so far...
My problem is that I am trying to get the resulting paths + what happened to them to write out into a text box. Maybe I am missing something completely obvious here, but I am getting the error:
CS0120 An object reference is required for the non-static field,
method, or property MainWindow.SearchRunOutputBox
when attempting to assign values inside an updater method I wrote.
I am very confused as I had assumed that a rich text box, already present on the form, would be it's own object? Again, maybe I am just missing something obvious here...
Code below:
using Microsoft.VisualStudio.Services.CircuitBreaker;
using Spire.Pdf.Exporting.XPS.Schema;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace Find_Move_PWP_PDF_s
{
public partial class MainWindow : Form
{
public MainWindow()
{
InitializeComponent();
}
public static void OutputBoxUpdater(string message, Color color)
{
SearchRunOutputBox.SuspendLayout();
SearchRunOutputBox.SelectionColor = color;
SearchRunOutputBox.AppendText(message);
SearchRunOutputBox.AppendText(Environment.NewLine);
SearchRunOutputBox.ScrollToCaret();
SearchRunOutputBox.ResumeLayout();
}
Is the text box object not created when InitializeComonent() is called as the MainWindow starts?
Included designer.cs below:
partial class MainWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.Label DirectoryPathLabel;
System.Windows.Forms.Label CreateSubFoldersLabel;
this.DirectoryPathInput = new System.Windows.Forms.TextBox();
this.SearchStartButton = new System.Windows.Forms.Button();
this.SearchProgressBar = new System.Windows.Forms.ProgressBar();
this.MovePDFsButton = new System.Windows.Forms.Button();
this.MovePDFsRunOutputBox = new System.Windows.Forms.RichTextBox();
this.MovesProgressBar = new System.Windows.Forms.ProgressBar();
this.SearchRunOutputBox = new System.Windows.Forms.RichTextBox();
DirectoryPathLabel = new System.Windows.Forms.Label();
CreateSubFoldersLabel = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// DirectoryPathLabel
//
DirectoryPathLabel.AccessibleDescription = "DirectoryPathLabel";
DirectoryPathLabel.AutoSize = true;
DirectoryPathLabel.BackColor = System.Drawing.SystemColors.Window;
DirectoryPathLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
DirectoryPathLabel.Location = new System.Drawing.Point(14, 23);
DirectoryPathLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
DirectoryPathLabel.Name = "DirectoryPathLabel";
DirectoryPathLabel.Size = new System.Drawing.Size(370, 25);
DirectoryPathLabel.TabIndex = 0;
DirectoryPathLabel.Text = "Please enter the desired search directory.";
//
// CreateSubFoldersLabel
//
CreateSubFoldersLabel.AccessibleDescription = "CreateSubFoldersLabel";
CreateSubFoldersLabel.AccessibleName = "CreateSubFoldersLabel";
CreateSubFoldersLabel.AutoSize = true;
CreateSubFoldersLabel.BackColor = System.Drawing.SystemColors.Window;
CreateSubFoldersLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
CreateSubFoldersLabel.Location = new System.Drawing.Point(14, 453);
CreateSubFoldersLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
CreateSubFoldersLabel.Name = "CreateSubFoldersLabel";
CreateSubFoldersLabel.Size = new System.Drawing.Size(725, 25);
CreateSubFoldersLabel.TabIndex = 5;
CreateSubFoldersLabel.Text = "Click here to move the password protected PDFs into subfolders labelled \"Locked\"." +
"";
//
// DirectoryPathInput
//
this.DirectoryPathInput.AccessibleDescription = "DirectoryPathInput";
this.DirectoryPathInput.Location = new System.Drawing.Point(424, 30);
this.DirectoryPathInput.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.DirectoryPathInput.Name = "DirectoryPathInput";
this.DirectoryPathInput.Size = new System.Drawing.Size(822, 23);
this.DirectoryPathInput.TabIndex = 1;
//
// SearchStartButton
//
this.SearchStartButton.AccessibleDescription = "SearchStartButton";
this.SearchStartButton.Location = new System.Drawing.Point(1278, 23);
this.SearchStartButton.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.SearchStartButton.Name = "SearchStartButton";
this.SearchStartButton.Size = new System.Drawing.Size(248, 30);
this.SearchStartButton.TabIndex = 2;
this.SearchStartButton.Text = "Start Search";
this.SearchStartButton.UseVisualStyleBackColor = true;
this.SearchStartButton.Click += new System.EventHandler(this.SearchStartButton_Click);
//
// SearchProgressBar
//
this.SearchProgressBar.AccessibleDescription = "SearchProgressBar";
this.SearchProgressBar.AccessibleName = "SearchProgressBar";
this.SearchProgressBar.Location = new System.Drawing.Point(14, 257);
this.SearchProgressBar.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.SearchProgressBar.Name = "SearchProgressBar";
this.SearchProgressBar.Size = new System.Drawing.Size(1512, 15);
this.SearchProgressBar.TabIndex = 3;
//
// MovePDFsButton
//
this.MovePDFsButton.AccessibleDescription = "MovePDFsButton";
this.MovePDFsButton.AccessibleName = "MovePDFsButton";
this.MovePDFsButton.Location = new System.Drawing.Point(767, 453);
this.MovePDFsButton.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.MovePDFsButton.Name = "MovePDFsButton";
this.MovePDFsButton.Size = new System.Drawing.Size(237, 25);
this.MovePDFsButton.TabIndex = 6;
this.MovePDFsButton.Text = "Move PDFs";
this.MovePDFsButton.UseVisualStyleBackColor = true;
//
// MovePDFsRunOutputBox
//
this.MovePDFsRunOutputBox.AccessibleDescription = "MovePDFsRunOutputBox";
this.MovePDFsRunOutputBox.AccessibleName = "MovePDFsRunOutputBox";
this.MovePDFsRunOutputBox.BackColor = System.Drawing.Color.WhiteSmoke;
this.MovePDFsRunOutputBox.Location = new System.Drawing.Point(14, 489);
this.MovePDFsRunOutputBox.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.MovePDFsRunOutputBox.Name = "MovePDFsRunOutputBox";
this.MovePDFsRunOutputBox.ReadOnly = true;
this.MovePDFsRunOutputBox.Size = new System.Drawing.Size(1511, 190);
this.MovePDFsRunOutputBox.TabIndex = 7;
this.MovePDFsRunOutputBox.Text = "";
//
// MovesProgressBar
//
this.MovesProgressBar.AccessibleDescription = "MovesProgressBar";
this.MovesProgressBar.AccessibleName = "MovesProgressBar";
this.MovesProgressBar.Location = new System.Drawing.Point(14, 687);
this.MovesProgressBar.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.MovesProgressBar.Name = "MovesProgressBar";
this.MovesProgressBar.Size = new System.Drawing.Size(1512, 15);
this.MovesProgressBar.TabIndex = 8;
//
// SearchRunOutputBox
//
this.SearchRunOutputBox.AccessibleDescription = "SearchRunOutputBox";
this.SearchRunOutputBox.AccessibleName = "SearchRunOutputBox";
this.SearchRunOutputBox.BackColor = System.Drawing.Color.WhiteSmoke;
this.SearchRunOutputBox.CausesValidation = false;
this.SearchRunOutputBox.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.SearchRunOutputBox.Location = new System.Drawing.Point(14, 60);
this.SearchRunOutputBox.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.SearchRunOutputBox.Name = "SearchRunOutputBox";
this.SearchRunOutputBox.ReadOnly = true;
this.SearchRunOutputBox.Size = new System.Drawing.Size(1511, 190);
this.SearchRunOutputBox.TabIndex = 4;
this.SearchRunOutputBox.Text = "";
//
// MainWindow
//
this.AccessibleDescription = "MainWindow";
this.AccessibleName = "MainWindow";
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ClientSize = new System.Drawing.Size(1540, 726);
this.Controls.Add(this.MovesProgressBar);
this.Controls.Add(this.MovePDFsRunOutputBox);
this.Controls.Add(this.MovePDFsButton);
this.Controls.Add(CreateSubFoldersLabel);
this.Controls.Add(this.SearchRunOutputBox);
this.Controls.Add(this.SearchProgressBar);
this.Controls.Add(this.SearchStartButton);
this.Controls.Add(this.DirectoryPathInput);
this.Controls.Add(DirectoryPathLabel);
this.DoubleBuffered = true;
this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.Name = "MainWindow";
this.Text = "Find and Move Password Protected PDF\'s";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox DirectoryPathInput;
private System.Windows.Forms.Button SearchStartButton;
private System.Windows.Forms.ProgressBar SearchProgressBar;
private System.Windows.Forms.Button MovePDFsButton;
private System.Windows.Forms.ProgressBar MovesProgressBar;
private System.Windows.Forms.RichTextBox MovePDFsRunOutputBox;
public System.Windows.Forms.RichTextBox SearchRunOutputBox;
}
}
I am wondering if there is a way to make the text box a static item? Or should I bet using something else to display the log?
I've tried initiating a new text box inside the OutBoxUpdater(), which got rid of the error, but doesn't seem to do anything. Or it did something, but not what I wanted lol.
public static void OutputBoxUpdater(string message, Color color)
{
RichTextBox SearchRunOutputBox = new();
SearchRunOutputBox.SuspendLayout();
SearchRunOutputBox.SelectionColor = color;
SearchRunOutputBox.AppendText(message);
SearchRunOutputBox.AppendText(Environment.NewLine);
SearchRunOutputBox.ScrollToCaret();
SearchRunOutputBox.ResumeLayout();
}
Edit:
As per the first comment from Steve, and sorry I didn't mention that I had tried this before, when I remove static from the method, it pushes the error down to where I am trying to call the method from.
using Spire.Pdf;
using System;
using System.Drawing;
using System.IO;
namespace Find_Move_PWP_PDF_s
{
public class PDFOpenToCheck
{
/// <summary>
/// Takes in a file path and attempts to open the file, throwing an error if it cannot, then saying it's password protected, and logging the filepath.
/// Also checks that the file is not empty, and if it is, logs the filepath to a different log.
/// </summary>
/// <param name="filePath">Current file path from stack.</param>
public void TryToOpenPDF(string filePath)
{
PdfDocument pdf = new();
FileInfo fi = new(filePath);
try
{
pdf.LoadFromFile(filePath);
MainWindow.OutputBoxUpdater(filePath + " successfully opened!", Color.Black);
}
catch (Exception)
{
//Not empty and is a PDF
if (fi.Length > 0 && filePath.EndsWith(".pdf"))
{
MainWindow.OutputBoxUpdater(filePath + " is password protected!", Color.Red);
LogWriters.WritePWPPDFLog(filePath);
}
//Is an empty file
else if (fi.Length <= 0)
{
MainWindow.OutputBoxUpdater(filePath + " is an empty file!", Color.Blue);
LogWriters.WriteEmptyFileLog(filePath);
}
//Is not empty and is not a PDF
else
{
MainWindow.OutputBoxUpdater(filePath + " is not a PDF!", Color.Green);
}
}
}
}
}
EDIT:
To show where TryToOpenPDF() is being called from.
namespace Find_Move_PWP_PDF_s
{
public static class TraverseDirectoryTree
{
/// <summary>
/// Recursive method to iterate through the directory structure below the provided start point.
/// In this application, will also perform PDF checking with Spire as it iterates (Line 74).
/// Uses stack based iteration.
/// </summary>
/// <param name="root">Starting parent directory.</param>
public static void TraverseTree(string root)
{
// Data structure to hold names of subfolders to be examined for files
// "Stack<T>" works by "first in last out" and could take a long time to build the initial stack before iteration begins
Stack<string> dirs = new();
if (!System.IO.Directory.Exists(root))
{
ArgumentException argumentException = new();
throw argumentException;
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = System.IO.Directory.GetDirectories(currentDir);
}
// "Unauthorized Access Exception" will be thrown if we do not have discovery permission on a folder or file.
catch (UnauthorizedAccessException e)
{
System.Diagnostics.Trace.WriteLine(e.Message);
//Console.WriteLine(e.Message);
continue;
}
//"Directory Not Found Exception" will be thrown if currentDir has been deleted by another application or thread after our call to Directory
catch (System.IO.DirectoryNotFoundException e)
{
System.Diagnostics.Trace.WriteLine(e.Message);
//Console.WriteLine(e.Message);
continue;
}
string[]? files;
try
{
files = System.IO.Directory.GetFiles(currentDir);
}
catch (UnauthorizedAccessException e)
{
System.Diagnostics.Trace.WriteLine(e.Message);
//Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
System.Diagnostics.Trace.WriteLine(e.Message);
//Console.WriteLine(e.Message);
continue;
}
// Perform the required action on each file here
foreach (string file in files)
{
try
{
PDFOpenToCheck.TryToOpenPDF(file);
}
catch (System.IO.FileNotFoundException e)
{
// If file was deleted by a separate application or thread since the call to "TraverseTree()", then just continue.
System.Diagnostics.Trace.WriteLine(e.Message);
//Console.WriteLine(e.Message);
continue;
}
catch (Exception e)
{
System.Diagnostics.Trace.WriteLine(e.Message);
//Console.WriteLine(e.Message);
}
}
// Push the subdirectories onto the stack for traversal
foreach (string str in subDirs)
dirs.Push(str);
}
}
}
}

Change OutputBoxUpdater() so it is NOT static:
public void OutputBoxUpdater(string message, Color color)
{
SearchRunOutputBox.SuspendLayout();
SearchRunOutputBox.SelectionColor = color;
SearchRunOutputBox.AppendText(message);
SearchRunOutputBox.AppendText(Environment.NewLine);
SearchRunOutputBox.ScrollToCaret();
SearchRunOutputBox.ResumeLayout();
}
Then change the signature of TryToOpenPDF() to receive MainForm as a parameter so you can use it:
public void TryToOpenPDF(string filePath, MainForm mf) {
// ... code ...
mf.OutputBoxUpdater(filePath + " successfully opened!", Color.Black);
// ... code ...
}
Note that I'm using the parameter name mf, and not the name of the Form itself.
Somewhere in MainForm, you are presumably calling TryToOpenPDF() but you haven't shown that yet.
It'd look something like:
// ... within MainForm code ...
PDFOpenToCheck pdf = new PDFOpenToCheck();
pdf.TryToOpenPDF("some file path", this);
Note we are passing the current instance of MainForm, the one that is already visible, via this!
--- Edit ---
So you now you have to make a choice, pass the reference first to TraverseTree(), which then passes it on to TryToOpenPDF(), or CHEAT with:
MainForm mf = Application.OpenForms.Cast<MainForm>().Where(x => (x is MainForm)).FirstOrDefault();
if (mf != null)
{
// ... do something with "mf" ...
}
Note that this assumes there will only ever be ONE instance of MainForm. This approach is generally frowned upon, though...

Related

the type or namespace Xtralayout does not exist in the namespace Devexpress

I am creating an USER INTERFACE in my programing class, and I am using Devexpress but it can not run because visual studio 2019 says:
the type or namespace Xtralayout does not exist in the namespace Devexpress
I am using C# and a plataform .NET
namespace Inventario_UI.Catalogos
{
partial class FrmListarProveedorcs
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.Root = new DevExpress.XtraLayout.LayoutControlGroup();
this.formAssistant1 = new DevExpress.XtraBars.FormAssistant();
this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.Root)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
this.SuspendLayout();
//
// layoutControl1
//
this.layoutControl1.Controls.Add(this.labelControl1);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 0);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.Root;
this.layoutControl1.Size = new System.Drawing.Size(800, 450);
this.layoutControl1.TabIndex = 0;
this.layoutControl1.Text = "layoutControl1";
//
// Root
//
this.Root.EnableIndentsWithoutBorders = DevExpress.Utils.DefaultBoolean.True;
this.Root.GroupBordersVisible = false;
this.Root.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1,
this.emptySpaceItem1});
this.Root.Name = "Root";
this.Root.Size = new System.Drawing.Size(800, 450);
this.Root.TextVisible = false;
//
// labelControl1
//
this.labelControl1.Location = new System.Drawing.Point(12, 12);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(63, 13);
this.labelControl1.StyleController = this.layoutControl1;
this.labelControl1.TabIndex = 4;
this.labelControl1.Text = "labelControl1";
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.labelControl1;
this.layoutControlItem1.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(780, 17);
this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem1.TextVisible = false;
//
// emptySpaceItem1
//
this.emptySpaceItem1.AllowHotTrack = false;
this.emptySpaceItem1.Location = new System.Drawing.Point(0, 17);
this.emptySpaceItem1.Name = "emptySpaceItem1";
this.emptySpaceItem1.Size = new System.Drawing.Size(780, 413);
this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
//
// FrmListarProveedorcs
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.layoutControl1);
this.Name = "FrmListarProveedorcs";
this.Text = "FrmListarProveedorcs";
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.Root)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup Root;
private DevExpress.XtraBars.FormAssistant formAssistant1;
private DevExpress.XtraEditors.LabelControl labelControl1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
}
}
```
Devexpress was not updated. That was why VS did not get the reference.
In visual Studio
go to extensiones-devexpress-project convert--upgrade all

How to scan specific string from excel and output is as new template?

I have to create a EXE. file in Visual Studio 2015 C#, the exe. file have to read a excel file and select some particular column from it, and then output these particular column as a new template.
Let's say, an excel originally have Column Name, Gender, Age.
I want to use the exe to select all the information in Column Name only, and output it as another new excel file.
Now I can read excel file and output it as another excel, but I dont know how to scan specific string from excel and output is as new template?
OP's Code from mispost:
using System;
using System.IO;
using System.Data.OleDb;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using Spire.Xls;
using Spire.Xls.Charts;
namespace Spire.Xls.Sample
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnRun;
private System.Windows.Forms.Button btnPDF;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.Label label1;
public DataGrid dataGrid1;
/// <summary>
/// Required designer variable.
/// </summary
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnRun = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.dataGrid1 = new System.Windows.Forms.DataGrid();
this.btnPDF = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// btnRun
//
this.btnRun.Location = new System.Drawing.Point(313, 494);
this.btnRun.Name = "btnRun";
this.btnRun.Size = new System.Drawing.Size(144, 30);
this.btnRun.TabIndex = 2;
this.btnRun.Text = "Apply filter";
this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
//
// btnClose
//
this.btnClose.Location = new System.Drawing.Point(633, 494);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(75, 30);
this.btnClose.TabIndex = 3;
this.btnClose.Text = "Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// label1
//
this.label1.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.label1.Location = new System.Drawing.Point(16, 14);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(528, 41);
this.label1.TabIndex = 4;
this.label1.Text = "This app can apply filter to Excel";
this.label1.Click += new System.EventHandler(this.label1_Click);
//
// dataGrid1
//
this.dataGrid1.AllowDrop = true;
this.dataGrid1.DataMember = "Group";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.ImeMode = System.Windows.Forms.ImeMode.On;
this.dataGrid1.Location = new System.Drawing.Point(313, 221);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(406, 249);
this.dataGrid1.TabIndex = 5;
//
// btnPDF
//
this.btnPDF.Location = new System.Drawing.Point(474, 494);
this.btnPDF.Name = "btnPDF";
this.btnPDF.Size = new System.Drawing.Size(144, 30);
this.btnPDF.TabIndex = 6;
this.btnPDF.Text = "Save as PDF";
this.btnPDF.Click += new System.EventHandler(this.btnPDF_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 18);
this.ClientSize = new System.Drawing.Size(731, 552);
this.Controls.Add(this.btnPDF);
this.Controls.Add(this.dataGrid1);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.btnRun);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Excel modifier";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
}
private void label1_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnRun_Click(object sender, System.EventArgs e)
{
Workbook workbook = new Workbook();
//Initailize worksheet
Worksheet sheet = workbook.Worksheets[0];
sheet.InsertDataTable((DataTable)this.dataGrid1.DataSource,true,1,1,-1,-1);
//Sets body style
CellStyle oddStyle = workbook.Styles.Add("oddStyle");
oddStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
oddStyle.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
oddStyle.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
oddStyle.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
oddStyle.KnownColor = ExcelColors.LightGreen1;
CellStyle evenStyle = workbook.Styles.Add("evenStyle");
evenStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
evenStyle.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
evenStyle.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
evenStyle.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
evenStyle.KnownColor = ExcelColors.LightTurquoise;
foreach( CellRange range in sheet.AllocatedRange.Rows)
{
if (range.Row % 2 == 0)
range.CellStyleName = evenStyle.Name;
else
range.CellStyleName = oddStyle.Name;
}
//Sets header style
CellStyle styleHeader = sheet.Rows[0].Style;
styleHeader.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
styleHeader.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
styleHeader.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
styleHeader.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
styleHeader.VerticalAlignment = VerticalAlignType.Center;
styleHeader.KnownColor = ExcelColors.Green;
styleHeader.Font.KnownColor = ExcelColors.White;
styleHeader.Font.IsBold = true;
sheet.AllocatedRange.AutoFitColumns();
sheet.AllocatedRange.AutoFitRows();
sheet.Rows[0].RowHeight = 20;
//Writes filter data
//CreateFilterData(sheet);
sheet.AutoFilters.Range = sheet.Range["A1:Z1"];
//append the sort column index and order by attributes
//workbook.DataSorter.SortColumns.Add(2, OrderBy.Ascending);
//workbook.DataSorter.SortColumns.Add(3, OrderBy.Ascending);
//set the range to sort.
//workbook.DataSorter.Sort(sheet["A1:Z999"]);
//save the xls to this path
workbook.SaveToFile(#"C:\Users\SmartEducationCoLtd\Desktop\sample.xls");
ExcelDocViewer( workbook.FileName );
//private void CreateFilterData(Worksheet sheet)
//{ }
private void btnClose_Click(object sender, System.EventArgs e)
{
Close();
}
private void Form1_Load(object sender, System.EventArgs e)
{
Workbook workbook = new Workbook();
//load from this excel path
workbook.LoadFromFile(#"C:\Users\SmartEducationCoLtd\Desktop\DataTableSample.xls");
//Initailize worksheet
Worksheet sheet = workbook.Worksheets[0];
this.dataGrid1.DataSource = sheet.ExportDataTable();
}
private void ExcelDocViewer( string fileName )
{
try
{
System.Diagnostics.Process.Start(fileName);
}
catch{}
}
}
You've set the data to the DataSource of your DataGrid to the data from the excel file via the line:
this.dataGrid1.DataSource = sheet.ExportDataTable();
in
private void Form1_Load(object sender, System.EventArgs e)
You could use the data directly from here, but I'm guessing you want to use it in this function:
private void btnRun_Click(object sender, System.EventArgs e)
You're accessing the DataTable you saved earlier using: (DataTable)this.dataGrid1.DataSource in the line: sheet.InsertDataTable((DataTable)this.dataGrid1.DataSource,true,1,1,-1,-1);. You could simply set it to a datatable variable using:
var dt = (DataTable)this.dataGrid1.DataSource;
OR set it a local instance level variable in the Form_Load method when you're setting the Datagrid's DataSource in the first place.
However you do it, once you have the datatable, you can access it using:
foreach(DataRow row in dt.Rows)
{
string name = row["Name"].ToString();
string gender = row["Gender"].ToString();
string age= row["Age"].ToString();
}
or whatever you want to with the data.

Windows Form Is Shown Blank When Opened

this is how the form shows when opened
http://imgur.com/JbE5I6m
what the form is supposed to look like
http://imgur.com/eTTiWUw
note: when in visual studio i did not start by making a win form app, this is for a private server for a game, its a .sln with 9 projects in it that all compile and work together, i am experimenting and seeing if its possible to do windows form in it, so far ive gotten good results, except for when i do the command (/wedit) to open it, the form shows blank, meanwhile in VS i have indeed added stuff to the form.
FrmWorldEdit.Designer.cs below
namespace WorldEdit
{
partial class FrmWorldEdit
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.listTiles = new System.Windows.Forms.ListView();
this.lblSearch = new System.Windows.Forms.Label();
this.tbxSearch = new System.Windows.Forms.TextBox();
this.btnToggle = new System.Windows.Forms.Button();
this.lblSelected = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// listTiles
//
this.listTiles.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listTiles.Location = new System.Drawing.Point(24, 69);
this.listTiles.Margin = new System.Windows.Forms.Padding(6);
this.listTiles.MultiSelect = false;
this.listTiles.Name = "listTiles";
this.listTiles.Size = new System.Drawing.Size(512, 492);
this.listTiles.TabIndex = 0;
this.listTiles.UseCompatibleStateImageBehavior = false;
this.listTiles.View = System.Windows.Forms.View.List;
this.listTiles.SelectedIndexChanged += new System.EventHandler(this.listTiles_SelectedIndexChanged);
//
// lblSearch
//
this.lblSearch.AutoSize = true;
this.lblSearch.Location = new System.Drawing.Point(19, 28);
this.lblSearch.Name = "lblSearch";
this.lblSearch.Size = new System.Drawing.Size(138, 25);
this.lblSearch.TabIndex = 1;
this.lblSearch.Text = "Search Tiles:";
//
// tbxSearch
//
this.tbxSearch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbxSearch.Location = new System.Drawing.Point(163, 26);
this.tbxSearch.Name = "tbxSearch";
this.tbxSearch.Size = new System.Drawing.Size(373, 31);
this.tbxSearch.TabIndex = 2;
this.tbxSearch.TextChanged += new System.EventHandler(this.tbxSearch_TextChanged);
//
// btnToggle
//
this.btnToggle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btnToggle.Location = new System.Drawing.Point(24, 617);
this.btnToggle.Name = "btnToggle";
this.btnToggle.Size = new System.Drawing.Size(512, 45);
this.btnToggle.TabIndex = 3;
this.btnToggle.Text = "Start Painting";
this.btnToggle.UseVisualStyleBackColor = true;
this.btnToggle.Click += new System.EventHandler(this.btnToggle_Click);
//
// lblSelected
//
this.lblSelected.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.lblSelected.AutoSize = true;
this.lblSelected.Location = new System.Drawing.Point(20, 577);
this.lblSelected.Name = "lblSelected";
this.lblSelected.Size = new System.Drawing.Size(197, 25);
this.lblSelected.TabIndex = 4;
this.lblSelected.Text = "Selected Tile: none";
//
// FrmWorldEdit
//
this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(564, 685);
this.Controls.Add(this.lblSelected);
this.Controls.Add(this.btnToggle);
this.Controls.Add(this.tbxSearch);
this.Controls.Add(this.lblSearch);
this.Controls.Add(this.listTiles);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.Margin = new System.Windows.Forms.Padding(6);
this.Name = "FrmWorldEdit";
this.Text = "World Editor Tool";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmWorldEdit_FormClosing);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListView listTiles;
private System.Windows.Forms.Label lblSearch;
private System.Windows.Forms.TextBox tbxSearch;
private System.Windows.Forms.Button btnToggle;
private System.Windows.Forms.Label lblSelected;
public FrmWorldEdit()
{
}
}
}
You have provided the content of the 'FrmWorldEdit.Designer.cs' file
Go to your 'FrmWorldEdit' file and make sure you have 'InitializeComponent' method call in the constructor, like so:
public partial class FrmWorldEdit : Form
{
public FrmWorldEdit()
{
InitializeComponent();
}
}
Dont forget to remove your constructor from the 'Designer' file if will decide to implement as I have suggested. Otherwise leave all as it is, but dont forget to add 'InitializeComponent()' method to your constructor in the 'Designer.cs' file
If the startup Form is blank and there is no compiler error.
Check if your Program.cs file is running the right Form, else it will run a form without context and will appear blank.
In this case the Program.cs file should look something like this:
using System;
using System.Windows.Forms;
namespace WorldEdit
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmWorldEdit());
}
}
}

How can I show a message box with details in WinForms?

Just now I noticed that Visual Studio shows a message box with details when a property is set to an invalid value. For example:
Is it possible to make this type of message box in WinForms?
I have tried the following code:
MessageBox.Show("Error in Division Fill.\n" + ex.Message,
"Information",
MessageBoxButtons.OK,
MessageBoxIcon.Information,
MessageBoxOptions.RightAlign);
But this produced the following error:
Error 24 The best overloaded method match for 'System.Windows.Forms.MessageBox.Show(string, string, System.Windows.Forms.MessageBoxButtons, System.Windows.Forms.MessageBoxIcon, System.Windows.Forms.MessageBoxDefaultButton)' has some invalid arguments
G:\Jagadeeswaran\Nov 17\MCS-SPS School\MCS-SPS School\Certificate\Transfer.cs 164 21 MCS-SPS School
How can I fix this error and get a message box that shows additional details?
As others have pointed out, you should write a custom dialog with the desired features. For help on this, you can look at the actual implementation used by the PropertyGrid for this dialog (perhaps with a decompiler) , which is, as of .NET 4.0, the System.Windows.Forms.PropertyGridInternal.GridErrorDlg type, internal to the System.Windows.Forms assembly.
I really wouldn't recommend it (could break in a future release), but if you're feeling really lazy, you can directly use this internal type using reflection.
// Get reference to the dialog type.
var dialogTypeName = "System.Windows.Forms.PropertyGridInternal.GridErrorDlg";
var dialogType = typeof(Form).Assembly.GetType(dialogTypeName);
// Create dialog instance.
var dialog = (Form)Activator.CreateInstance(dialogType, new PropertyGrid());
// Populate relevant properties on the dialog instance.
dialog.Text = "Sample Title";
dialogType.GetProperty("Details").SetValue(dialog, "Sample Details", null);
dialogType.GetProperty("Message").SetValue(dialog, "Sample Message", null);
// Display dialog.
var result = dialog.ShowDialog();
Result:
You need to set following properties of Form to create a custom Dialog/Message window.
AcceptButton
CancelButton
FormBorderStyle=FixedDialog
MaximizeBox=False
MinimizeBox=False
ShowIcon=False
ShowInTaskBar=False
StartPosition=CenterParent
Now, use ShowDialog() method to show custom dialog.
MyDialog dialog=new MyDialog();
DialogResult result=dialog.ShowDialog();
if(result == DialogResult.OK)
{
//
}
For more information on Dialog read MSDN article - Dialog Boxes (Visual C#)
just write your own dialog, there is no overload like you want to show method.
Based on the answer above (which I upvoted) I wrote the following. Paste this into a form you generated using a VS template and it should work, maybe with few tweaks.
My code:
using System;
using System.Windows.Forms;
namespace MessageBoxWithDetails
{
/// <summary>
/// A dialog-style form with optional colapsable details section
/// </summary>
public partial class MessageBoxWithDetails : Form
{
private const string DetailsFormat = "Details {0}";
public MessageBoxWithDetails(string message, string title, string details = null)
{
InitializeComponent();
lblMessage.Text = message;
this.Text = title;
if (details != null)
{
btnDetails.Enabled = true;
btnDetails.Text = DownArrow;
tbDetails.Text = details;
}
}
private string UpArrow
{
get
{
return string.Format(DetailsFormat, char.ConvertFromUtf32(0x25B4));
}
}
private string DownArrow
{
get
{
return string.Format(DetailsFormat, char.ConvertFromUtf32(0x25BE));
}
}
/// <summary>
/// Meant to give the look and feel of a regular MessageBox
/// </summary>
public static void Show(string message, string title, string details = null)
{
new MessageBoxWithDetails(message, title, details).ShowDialog();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Change these properties now so the label is rendered so we get its real height
var height = lblMessage.Height;
SetMessageBoxHeight(height);
}
private void SetMessageBoxHeight(int heightChange)
{
this.Height = this.Height + heightChange;
if (this.Height < 150)
{
this.Height = 150;
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnDetails_Click(object sender, EventArgs e)
{
// Re-anchoring the controls so they stay in their place while the form is resized
btnCopy.Anchor = AnchorStyles.Top;
btnClose.Anchor = AnchorStyles.Top;
btnDetails.Anchor = AnchorStyles.Top;
tbDetails.Anchor = AnchorStyles.Top;
tbDetails.Visible = !tbDetails.Visible;
btnCopy.Visible = !btnCopy.Visible;
btnDetails.Text = tbDetails.Visible ? UpArrow : DownArrow;
SetMessageBoxHeight(tbDetails.Visible ? tbDetails.Height + 10 : -tbDetails.Height - 10);
}
private void btnCopy_Click(object sender, EventArgs e)
{
Clipboard.SetText(tbDetails.Text);
}
}
Designer auto generated code (it should give you an idea regarding what to put in the form if you don't want to paste it):
namespace MessageBoxWithDetails
{
partial class MessageBoxWithDetails
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnClose = new System.Windows.Forms.Button();
this.btnDetails = new System.Windows.Forms.Button();
this.btnCopy = new System.Windows.Forms.Button();
this.lblMessage = new System.Windows.Forms.Label();
this.tbDetails = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.Location = new System.Drawing.Point(267, 37);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(75, 23);
this.btnClose.TabIndex = 0;
this.btnClose.Text = "Close";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnDetails
//
this.btnDetails.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btnDetails.Enabled = false;
this.btnDetails.Location = new System.Drawing.Point(12, 37);
this.btnDetails.Name = "btnDetails";
this.btnDetails.Size = new System.Drawing.Size(75, 23);
this.btnDetails.TabIndex = 1;
this.btnDetails.Text = "Details";
this.btnDetails.UseVisualStyleBackColor = true;
this.btnDetails.Click += new System.EventHandler(this.btnDetails_Click);
//
// btnCopy
//
this.btnCopy.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btnCopy.Location = new System.Drawing.Point(93, 37);
this.btnCopy.Name = "btnCopy";
this.btnCopy.Size = new System.Drawing.Size(102, 23);
this.btnCopy.TabIndex = 4;
this.btnCopy.Text = "Copy To Clipboard";
this.btnCopy.UseVisualStyleBackColor = true;
this.btnCopy.Visible = false;
this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click);
//
// lblMessage
//
this.lblMessage.AutoSize = true;
this.lblMessage.Location = new System.Drawing.Point(12, 9);
this.lblMessage.MaximumSize = new System.Drawing.Size(310, 0);
this.lblMessage.Name = "lblMessage";
this.lblMessage.Size = new System.Drawing.Size(35, 13);
this.lblMessage.TabIndex = 5;
this.lblMessage.Text = "label1";
//
// tbDetails
//
this.tbDetails.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.tbDetails.Location = new System.Drawing.Point(12, 68);
this.tbDetails.MaximumSize = new System.Drawing.Size(328, 100);
this.tbDetails.Multiline = true;
this.tbDetails.Name = "tbDetails";
this.tbDetails.ReadOnly = true;
this.tbDetails.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.tbDetails.Size = new System.Drawing.Size(328, 100);
this.tbDetails.TabIndex = 6;
this.tbDetails.Visible = false;
//
// MessageBoxWithDetails
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(354, 72);
this.Controls.Add(this.tbDetails);
this.Controls.Add(this.lblMessage);
this.Controls.Add(this.btnCopy);
this.Controls.Add(this.btnDetails);
this.Controls.Add(this.btnClose);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "MessageBoxWithDetails";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.Button btnDetails;
private System.Windows.Forms.Button btnCopy;
private System.Windows.Forms.Label lblMessage;
private System.Windows.Forms.TextBox tbDetails;
}
}
I also encounter the same problem to you. I suggest you use windowsAPIcode pack.
This site will be a great help. Just follow the instructions properly: http://www.developerfusion.com/article/71793/windows-7-task-dialogs/
You can simply do this:
catch (Exception error)
{
throw new Exception("Error with details button! \n"+error);
}
The text in "" is "Adicionar Fotografia".
Note: this code works fine when running the app(.exe) while running in editor it doesn't work and makes sense.
This is an example of the code above:

C# issue: How do I manipulate a Textbox on one form from another form?

I'm trying to create my own error window for the project I am working on. When I show my error window I have no way to pass the error message, and user message to the Error window because the "ErrorMessage.Text" cannot be seen in the classes I make.
I went into the form designer generated code and tried to make the TextBox static, but that just breaks things. Can I make a TextBox public / static so I can change it from another form?
How do I make a TextBox Static Public so I can manipulate it across other forms, or is there another method for doing this?
EDIT:
Okay, for more information...
I have my own Form created. It is called "formErrorWindow." I need to display the form that i've pre-designed with the message set from another form. The only way I can do this is if I create a Function in the windows designer area for the form, and I set the variables with "this.errorMsg.text = error." The only way I can see that function is if I set it to static. If I set the function to Static, when I try and put "this.errorMsg.Text = error" I get this error: An object reference is required for the non-static field, method, or property.
Here is what I've attempted:
namespace LCR_ShepherdStaffupdater_1._0
{
partial class formErrorWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
public System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
///
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
// ********* HERE IS THE FUNCTION THAT IVE ADDED BELOW. THIS WOULD WORK BUT.... *********
public static void showError(string errorTitle, string usrMsg, string errorMsg)
{
formErrorWindow errorWindow = new formErrorWindow();
errorMsgItem.Text = errorMsg;
errorTitleItem.Text = "Error! : " + errorTitle;
usrMsgItem.Text = usrMsg;
errorWindow.ShowDialog();
}
// ********* HERE IS THE FUNCTION THAT IVE ADDED ABOVE. THIS WOULD WORK BUT.... *********
// ********* I get an error: "An object reference is required for the non-static field, method, or property." *********
public void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(formErrorWindow));
this.usrMsgItem = new System.Windows.Forms.TextBox();
this.errorTitleItem = new System.Windows.Forms.Label();
this.errorMsgItem = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.label2 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// usrMsgItem
//
this.usrMsgItem.Enabled = false;
this.usrMsgItem.Location = new System.Drawing.Point(13, 37);
this.usrMsgItem.Multiline = true;
this.usrMsgItem.Name = "usrMsgItem";
this.usrMsgItem.Size = new System.Drawing.Size(334, 81);
this.usrMsgItem.TabIndex = 0;
this.usrMsgItem.Text = "Undefined";
//
// errorTitleItem
//
this.errorTitleItem.AutoSize = true;
this.errorTitleItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.errorTitleItem.ForeColor = System.Drawing.Color.Red;
this.errorTitleItem.Location = new System.Drawing.Point(12, 9);
this.errorTitleItem.Name = "errorTitleItem";
this.errorTitleItem.Size = new System.Drawing.Size(152, 20);
this.errorTitleItem.TabIndex = 1;
this.errorTitleItem.Text = "Error! : Undefined";
//
// errorMsgItem
//
this.errorMsgItem.Enabled = false;
this.errorMsgItem.Location = new System.Drawing.Point(0, 21);
this.errorMsgItem.Multiline = true;
this.errorMsgItem.Name = "errorMsgItem";
this.errorMsgItem.Size = new System.Drawing.Size(329, 101);
this.errorMsgItem.TabIndex = 2;
this.errorMsgItem.Text = "Undefined";
//
// button1
//
this.button1.Location = new System.Drawing.Point(272, 256);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Continue";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.errorMsgItem);
this.panel1.Location = new System.Drawing.Point(12, 124);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(335, 126);
this.panel1.TabIndex = 4;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(68, 1);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(189, 17);
this.label2.TabIndex = 3;
this.label2.Text = "Technical Error Message";
//
// formErrorWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.ClientSize = new System.Drawing.Size(359, 290);
this.Controls.Add(this.panel1);
this.Controls.Add(this.button1);
this.Controls.Add(this.errorTitleItem);
this.Controls.Add(this.usrMsgItem);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "formErrorWindow";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Error!";
this.VisibleChanged += new System.EventHandler(this.formErrorWindow_VisibleChanged);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label2;
public System.Windows.Forms.TextBox usrMsgItem;
public System.Windows.Forms.Label errorTitleItem;
public System.Windows.Forms.TextBox errorMsgItem;
}
}
Look for the function I've added above. How do I get that to compile and do what I want it to do WITHOUT that error I keep getting: An object reference is required for the non-static field, method, or property.
I would just pass the message as a constructor parameter.
MyMessageBox messageBox = new MyMessageBox("My error message");
messageBox.Show();
Yes! have a function made public that can receive this text:
pseudo: public void updateTextBox(string new_text)
and have the function update the textbox from there.
don't mix UI with logic.
public partial class Form1 : Form
{
private static TextBox box;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// box
box = new TextBox();
box.Location = new System.Drawing.Point(87, 230);
box.Name = "box";
box.Size = new System.Drawing.Size(100, 20);
box.TabIndex = 1;
this.Controls.Add(box);
}
}
You can make the TextBox public first of.
Second make a static form(name of your form) variable and put the form there each time its loaded...
This is not a good solution in my eyes but without knowing more about your design its the best i can come up with...
Allowing public access to an object contained in your class may be a design. How about writing a property in the error window class called ErrorText and inside that property set the ErrorMessage.Text to the passed string? Or am I missing something?
If you really want to go with accessing the controls directly:
public Form2(Form1 form1)
{
InitializeComponent();
Owner = form1;
_form1 = form1;
}
now you can access the controls on form1 this way:
_form1.theForm1ControlName
You could create a method in the Error window's class which could be something like:
public void SetErrorText(string errorText)
{
this.ErrorMessage.Text = errorText; // assuming the TextBox' ID is ErrorMessage.
}
Sounds like you're on the right track by adding the public function you did, but you shouldn't have to make it static. As a general rule, if you have to go into the Designer Generated Code, something isn't right, so let's get out of there - it doesn't mean you can't add code to the form, obviously, but don't do it in that section :)
The error you're getting I believe originates from having a non-instantiated object (i.e. creating the error form like:
formErrorWindow myErrorWindow;
as opposed to instantiating it / creating an instance of it like so:
formErrorWindow myErrorWindow = new formErrorWindow();
You've made the function static, so you can see it from anywhere, however that function can't actually do anything because the form that it runs on doesn't exist yet until you use " = new formErrorWindow();".
So if I'm in a form called "MainForm" and I want to show an error, using the name of the function you provided it would be done like this:
formErrorWindow myErrorWindow = new formErrorWindow();
myErrorWindow.showError("Title", "User Message Here", "Error Message Here");
myErrorWindow.ShowDialog();
The key is to make sure nothing is static and then make sure you're initializing the formErrorWindow with = new formErrorWindow();
Pass the TextBox to the function/method like so
public static void myFunc(TextBox textBox1)
{
textBox1.Text = "do stuff";
{

Categories