I am having a treeview initially with a root node when form is loaded. I will add child node as some.txt file at the runtime by selecting an option as Addnew from contextmenu which was displayed when the user right clicks on the root node. Now what i need is if the tree has child node appended to the Root and if user tries to create a new node by clicking the option addnew from context menu i would like to display an error as only one child allowed.
My sample code to add a child node is as follows
private void AddNew_Click(object sender, EventArgs e)
{
//if (tvwACH.Nodes.Count==1)
//{
// MessageBox.Show("Only One File allowed");
//}
//else
//{
if (tvwACH.SelectedNode.Text != null)
{
string strSelectedNode = tvwACH.SelectedNode.Text.ToString();
switch (strSelectedNode)
{
case "ACH":
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "(*.txt)|*.txt";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.ValidateNames = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileName = saveFileDialog1.FileName;
if (FileName.Contains(" \\/:*?<>|"))
{
MessageBox.Show("File name should not contain \\/:*?<>|", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
FileName = saveFileDialog1.FileName;
TreeNode newNode = new TreeNode(FileName);
newNode.SelectedImageIndex = 1;
tvwACH.SelectedNode.Nodes.Add(newNode);
TreeNode NodeFileHeader = newNode.Nodes.Add("FileHeader");
myStream.Close();
}
}
}
break;
}
case "FileHeader":
{
sr = new StreamReader(FileName);
strLen = sr.ReadLine();
if (strLen == null)
{
sr.Close();
Form frmFileHeader = new frmFileHeader(this);
frmFileHeader.ShowDialog(this);
}
else
{
MessageBox.Show("Only One File Header is allowed for a file", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
break;
}
case "BatchHeader":
{
Form frmBatch = new frmBatch(this);
frmBatch.ShowDialog();
break;
}
}
}
//}
}
No user ever likes to get slapped with a message box that tells her she did something dumb. Improve your user interface, simply disable the menu item if it shouldn't be used. Use the context menu's Opening event, like this:
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) {
addNewToolStripMenuItem.Enabled = tvwACH.Nodes.Count > 1;
}
Related
I'm able to select files through through folder browser dialog but I need to show the selected file in treelist control (Note: I'm using WPF and devexpress controls).
How can I achieve this? Please check the image:
*******************Code**********************
private void loadFilePst ()
{
try
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".pst";
dlg.Filter = "PST Files(*.pst)|*.pst";
Nullable<bool> output = dlg.ShowDialog();
if (dlg.ShowDialog() != true)
return;
using (Stream stream = dlg.OpenFile())
{
}
//if(output == true)
//{
// stgPath = dlg.FileName;
// string fileName = dlg.FileName;
// treePstSelect.Visibility = Visibility.Visible;
//}
//System.Windows.MessageBox.Show("Hola");
}
catch(Exception ae)
{
System.Windows.MessageBox.Show(ae.Message);
}
}
I have discovered that I am beginning to use the same code for a few different click events. I have a MDI form and there are "master children" as I call them that will open other children associated with the master. This is the master/detail thing going on. An example is the Company master child will have buttons to open the Contact, Industry, etc associated with the Company. Below is a sample of the code that opens the Contact child form. This code is also being used for the others as well.
What I am looking to do is to be able to use just one and fill in the button, form, message, and a connection label between Company and Contact. The code at the botton is what I have so far and I marked the lines that need to be changed with what I'm looking for. The lines with the single arrow "seem" to work but the multi arrow line can't get it right. Providing both for comparison reasons.
Could someone look this/these over and see what I'm doing wrong (or missing) in the consolidated code?
Thanks...John
//CODE TO OPEN THE CONTACT CHILD FORM
private void btnCompanyContact_Click(object sender, EventArgs e)
{
bool isOpen = false;
foreach (Form f in Application.OpenForms)
{
if (f is frmContact)
{
isOpen = true;
MessageBox.Show("The Contact list is already open.", "INFORMATION", MessageBoxButtons.OK);
f.BringToFront();
f.Controls["lblRecordID"].Text = lblCompanyID.Text;
break;
}
}
if (!isOpen)
{
frmContact contact = new frmContact();
contact.MdiParent = this.MdiParent;
contact.ReceiveValue(lblCompanyID.Text);
contact.StartPosition = FormStartPosition.Manual;
contact.Location = new Point(100, 100);
contact.Show();
}
else
{
//do nothing
}
}
//CONSOLIDATE ALL THE BUTTON OPENING INTO THIS ROUTINE
private void OpenCompanyInformationForm(Button btn, Form name, string message, string lbl)
{
bool isOpen = false;
foreach (Form f in Application.OpenForms)
{
-> if (f == name)
{
isOpen = true;
-> MessageBox.Show("The " + message + " list is already open.", "INFORMATION", MessageBoxButtons.OK);
f.BringToFront();
-> f.Controls[lbl].Text = lblCompanyID.Text;
break;
}
}
if (!isOpen)
{
->->-> frmContact contact = new frmContact();
contact.MdiParent = this.MdiParent;
contact.ReceiveValue(lblCompanyID.Text);
contact.StartPosition = FormStartPosition.Manual;
contact.Location = new Point(100, 100);
contact.Show();
}
else
{
//do nothing
}
}
To perfom the custom function ReceiveValue you need to create a derived class from Form
and create all you forms from this derived class
public class ContactBase : Form
{
public void ReceiveValue(string p_Value)
{
Button button = (Button)this.Controls["lblRecordID"];
if (button == null) return;
button.Text = p_Value;
}
}
private void OpenCompanyInformationForm(Form name)
{
bool isOpen = false;
foreach (Form f in Application.OpenForms)
{
// Just to compare, you can use the Name property
-> if (f.Name == name.Name)
{
isOpen = true;
// If the message is just a name of form, you can use Name or Text property
// in this case you can supress message param
-> MessageBox.Show("The " + f.Text + " list is already open.", "INFORMATION", MessageBoxButtons.OK);
f.BringToFront();
// If the ReceiveValue is just to pass the text of lblCompanyID for lblRecordID button, you can use the function here
-> ((ContactBase)name).ReceiveValue(lblCompanyID.Text);
break;
}
}
if (!isOpen)
{
->->-> ContactBase contact = (ContactBase)Activator.CreateInstance(name.GetType());
contact.MdiParent = this.MdiParent;
contact.ReceiveValue(lblCompanyID.Text);
contact.StartPosition = FormStartPosition.Manual;
contact.Location = new Point(100, 100);
contact.Show();
}
else
{
//do nothing
}
}
I have a rtbDoc(simple word app)that you can change the back color using the colorDialog,
it does not change the color back to white if you load a new doc, so the color you picked stays the same, how would i make it refresh every time you load a new Doc ?
Here is what i have for the Back color
try
{
colorDialog1.Color = rtbDoc.BackColor;
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
rtbDoc.BackColor = colorDialog1.Color;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
And here is the code for the New button
if (rtbDoc.Modified == true)
{
DialogResult answer;
answer = MessageBox.Show("Save Document before creating a new document?", "Unsaved Document",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (answer == DialogResult.No)
{
currentFile = "";
this.Text = "Editor: New Document";
rtbDoc.Modified = false;
rtbDoc.Clear();
return;
}
else
{
saveToolStripMenuItem_Click(this, new EventArgs());
rtbDoc.Modified = false;
rtbDoc.Clear();
currentFile = "";
this.Text = "New Document";
return;
}
}
else
{
currentFile = "";
this.Text = "New Document";
rtbDoc.Modified = false;
rtbDoc.Clear();
return;
}
Or is it some thing i should change in the formLoad event ?
Add this code where you open new document.
rtbDoc.BackColor = Color.White;
I have made an Address Book WinForm in C# and would like to know how to print it as a text file, how would I go about doing this?
I have displayed everything in a DataGridView, I would ideally just like to print the information in the table as text.
you can try like this...
[STAThread]
static void Main()
{
Application.Run(new PrintPreviewDialog());
}
private void btnOpenFile_Click(object sender, System.EventArgs e)
{
openFileDialog.InitialDirectory = #"c:\";
openFileDialog.Filter = "Text files (*.txt)|*.txt|" +
"All files (*.*)|*.*";
openFileDialog.FilterIndex = 1; // 1 based index
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
StreamReader reader = new StreamReader(openFileDialog.FileName);
try
{
strFileName = openFileDialog.FileName;
txtFile.Text = reader.ReadToEnd();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
finally
{
reader.Close();
}
}
}
private void btnSaveFile_Click(object sender, System.EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = #"c:\";
sfd.Filter = "Text files (*.txt)|*.txt|" +
"All files (*.*)|*.*";
sfd.FilterIndex = 1; // 1 based index
if (strFileName != null)
sfd.FileName = strFileName;
else
sfd.FileName = "*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(strFileName,false);
try
{
strFileName = sfd.FileName;
writer.Write(txtFile.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
finally
{
writer.Close();
}
}
}
//here you can print form as text file by clicking on the button..
private void btnPageSetup_Click(object sender, System.EventArgs e)
{
PageSetupDialog psd = new PageSetupDialog();
psd.Document = printDocument;
psd.ShowDialog();
}
private void btnPrint_Click(object sender, System.EventArgs e)
{
PrintDialog pdlg = new PrintDialog();
pdlg.Document = printDocument;
if (pdlg.ShowDialog() == DialogResult.OK)
{
try
{
printDocument.Print();
}
catch(Exception ex)
{
MessageBox.Show("Print error: " + ex.Message);
}
}
}
private void btnPrintPreview_Click(object sender, System.EventArgs e)
{
PrintPreviewDialog ppdlg = new PrintPreviewDialog();
ppdlg.Document = printDocument;
ppdlg.ShowDialog();
}
private void pdPrintPage(object sender, PrintPageEventArgs e)
{
float linesPerPage = 0;
float verticalOffset = 0;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;
int linesPrinted = 0;
String strLine = null;
linesPerPage = e.MarginBounds.Height / currentFont.GetHeight(e.Graphics);
while (linesPrinted < linesPerPage &&
((strLine = stringReader.ReadLine())!= null ))
{
verticalOffset = topMargin + (linesPrinted * currentFont.GetHeight(e.Graphics));
e.Graphics.DrawString(strLine, currentFont, Brushes.Black, leftMargin, verticalOffset);
linesPrinted++;
}
if (strLine != null)
e.HasMorePages = true;
else
e.HasMorePages = false;
}
private void pdBeginPrint(object sender, PrintEventArgs e)
{
stringReader = new StringReader(txtFile.Text);
currentFont = txtFile.Font;
}
private void pdEndPrint(object sender, PrintEventArgs e)
{
stringReader.Close();
MessageBox.Show("Done printing.");
}
}
Preview and Print from Your Windows Forms App with the .NET Printing Namespace
http://msdn.microsoft.com/en-us/magazine/cc188767.aspx
It's a little old (2003) but still looks relevent.
you should give more details on what you want to do.
how do you intend to print the form as text file? How do you convert the graphics like labels, buttons and other controls into text?
what you ask is possible and you can control every aspect of the printed content in both ways graphic rendering or text only, have a look here as starting point:
Windows Forms Print Support
The simpliest way is to create a text file and write the values in it. Like this:
var textFile = File.CreateText("Address.txt");
textFile.WriteLine("Name: Fischermaen");
textFile.Close();
In my application I am using a tree view. When the user clicks on the [+] to expand a node, that node changes to the selected node. How can I stop this?
private void tvFileStructure_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (e.Node.Text != "Network")
{
int unauthorisedAccessExceptions = 0;
try
{
TreeNode newSelected = e.Node;
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
TreeNode child = newSelected.FirstNode;
if (child.Level < 3)
{
while (child != null)
{
// Only try to populate if there aren't any children
if (child.FirstNode == null)
{
DirectoryInfo[] subDirs = ((DirectoryInfo)child.Tag).GetDirectories();
if (subDirs.Length != 0)
{
getDirectories(subDirs, child);
}
}
child = child.NextNode;
}
}
}
catch (UnauthorizedAccessException)
{
unauthorisedAccessExceptions++;
}
if (unauthorisedAccessExceptions > 0)
{
MessageBox.Show("There were " + unauthorisedAccessExceptions.ToString() + " folder(s) that you do not have access to.", "Warning...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
As Hans mentioned this is not the default behavior of the standard WinForms TreeView. However, you can cancel the selection changing in the BeforeSelect event:
void tvFileStructure_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
if (iDontWantToSelectThis)
{
e.Cancel = true;
}
}