In my program, when I click a particular row in DataGridView, if that row contains "\" it should pop up an error message that "\ is not allowed in name or in path". I don't know how to do that.
Here is the code:
namespace OVF_ImportExport
{
public partial class Form1 : Form
{
string sName = "";
string sPath = "";
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
sName = row.Cells[0].Value.ToString();
sPath = row.Cells[1].Value.ToString();
}
}
private void BtnCreate_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
StreamWriter file = new StreamWriter("Export.bat");
file.WriteLine("c: ");
file.WriteLine("cd \\");
file.WriteLine("cd Program Files ");
file.WriteLine("cd VMware");
file.WriteLine("cd VMware OVF Tool");
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
sName = row.Cells[0].Value.ToString();
sName = sName.Trim();
sPath = row.Cells[1].Value.ToString();
file.WriteLine("start ovftool.exe --powerOffSource vi://" + TxtUsername.Text + ":" + TxtPassword.Text + "#"
+ TxtIP.Text + sPath + " " + "\"" + TxtBrowsepath.Text + "\\" + sName + "\\" + sName + ".ovf" + "\"" + Environment.NewLine);
}
file.WriteLine("pause");
MessageBox.Show("Batch File Created","Batch File");
file.Close();
}
try using this:
// Attach DataGridView events to the corresponding event handlers.
this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
method for above event handler:
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
// Validate the CompanyName entry by disallowing empty strings.
if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
{
if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"Company Name must not be empty";
e.Cancel = true;
}
}
}
Related
I develop simple application for renaming locally stored emails. Emails are loaded in a listbox and there is a button which does renaming. The problem is that I can rename three email and than the application crushes. No specific error reported. Here is my code...
namespace EmailFilenameRename
{
public partial class Form1 : Form
{
CultureInfo deCulture = new CultureInfo("de-DE");
public Form1()
{
InitializeComponent();
}
private static string[] getAddressParts(string address)
{
var splittedAdress = address.Split(' ');
return splittedAdress.Last().Trim().StartsWith("<")
? new[] { string.Join(" ", splittedAdress.Take(splittedAdress.Length - 1)), splittedAdress.Last().Trim(' ', '<', '>') }
: splittedAdress;
}
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo d = new DirectoryInfo(#"C:\...\in");
FileInfo[] Files = d.GetFiles("*.eml");
foreach (FileInfo file in Files)
{
listBox1.Items.Add(file.Name);
}
}
private void button1_Click(object sender, EventArgs e)
{
string oldName = #"C:\...\in\" + listBox1.GetItemText(listBox1.SelectedItem);
var mail = Sasa.Net.Mail.Message.Parse(File.ReadAllText(oldName));
string dt = mail.Headers["Date"].ToString();
DateTimeOffset originalTime = DateTimeOffset.Parse(dt, deCulture);
DateTime utcTime = originalTime.UtcDateTime.ToLocalTime();
string sTime = utcTime.ToString("yyyyMMdd HHmm");
string[] sFrom = getAddressParts(mail.From.ToString());
string sSubject = mail.Subject.Replace(":", "");
String newName = #"C:\...\in\renamed\" + sTime + " -- " + sFrom[1] + " -- " + sSubject + ".eml";
File.Copy(oldName, newName);
File.Delete(oldName);
}
}
}
I have also tried with MimeKit... the same problem exists.
This question already has answers here:
Open existing file, append a single line
(9 answers)
Closed 4 years ago.
Basicly I'm writing a fake malware, which will write in a .txt the Session username of the person which clicked on it. The problem is that when someone execute it will erase the previous lines.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Text = "Fake Malware";
}
private void Form1_Load(object sender, EventArgs e)
{
string createText = " just clicked on the fake Malware";
File.WriteAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName + createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
private void zig(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("Link to a warning message on click, nothing important.");
string createText = " just clicked on the fake Malware";
File.WriteAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName+ createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
}
I think what you are looking for is AppendAllText:
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", "Wow it worked :)");
Here is the fix
private void Form1_Load(object sender, EventArgs e)
{
string createText = " just clicked on the fake Malware";
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName + createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
private void zig(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("#");
string createText = " just clicked on the fake Malware";
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName+ createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
}
}
We have a project to do a program to add and remove universities and had five universities inside our .txt file to show them in our ComboBox.
But it doesn`t work and shows this error:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Note: It's a Windows Form.
So here's the code:
public partial class Form1 : Form
{
university[] univ = new university[10];
struct university
{
public string uni;
public string prov;
public string city;
public string population;
public string programs;
public string tuition;
public string residence;
}
public Form1()
{
InitializeComponent();
}
private void pictureBox4_Click(object sender, EventArgs e)
{
MessageBox.Show("If you want to check the infomation, click on the combo box and then choose the University of your choice.\n- Click the black button to add a university to the list after filling in everything. \n- Click the red button to remove a university after selecting it.");
}
private void Form1_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("Universities.txt"); // object
String line;
try
{
for (int i = 0; i < univ.Length; i++)
{
line = sr.ReadLine();
string[] sPlit = line.Split(',');
univ[i].uni = sPlit[0];
univ[i].prov = sPlit[1];
univ[i].city = sPlit[2];
univ[i].population = sPlit[3];
univ[i].programs = sPlit[4];
univ[i].tuition = sPlit[5];
univ[i].residence = sPlit[6];
comboBox1.Items.Add(univ[i].uni);
}
sr.Close();
}
catch (Exception p) //catches errors
{
Console.WriteLine("Exception: " + p.Message);
}
finally //final statement before closing
{
Console.WriteLine("Executing finally block.");
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
{
listBox1.Items.Clear();
pictureBox1.Image = Properties.Resources._1;
listBox1.Items.Add("Province: " + univ[0].prov);
listBox1.Items.Add("City: " + univ[0].city);
listBox1.Items.Add("Population: " + univ[0].population);
listBox1.Items.Add("Programs: " + univ[0].programs);
listBox1.Items.Add("Tuition: $" + univ[0].tuition);
listBox1.Items.Add("Residence: $" + univ[0].residence);
}
else if (comboBox1.SelectedIndex == 1)
{
listBox1.Items.Clear();
pictureBox1.Image = Properties.Resources._2;
listBox1.Items.Add("Province: " + univ[1].prov);
listBox1.Items.Add("City: " + univ[1].city);
listBox1.Items.Add("Population: " + univ[1].population);
listBox1.Items.Add("Programs: " + univ[1].programs);
listBox1.Items.Add("Tuition: $" + univ[1].tuition);
listBox1.Items.Add("Residence: $" + univ[1].residence);
}
else if (comboBox1.SelectedIndex == 2)
{
listBox1.Items.Clear();
pictureBox1.Image = Properties.Resources._3;
listBox1.Items.Add("Province: " + univ[2].prov);
listBox1.Items.Add("City: " + univ[2].city);
listBox1.Items.Add("Population: " + univ[2].population);
listBox1.Items.Add("Programs: " + univ[2].programs);
listBox1.Items.Add("Tuition: $" + univ[2].tuition);
listBox1.Items.Add("Residence: $" + univ[2].residence);
}
else if (comboBox1.SelectedIndex == 3)
{
listBox1.Items.Clear();
pictureBox1.Image = Properties.Resources._4;
listBox1.Items.Add("Province: " + univ[3].prov);
listBox1.Items.Add("City: " + univ[3].city);
listBox1.Items.Add("Population: " + univ[3].population);
listBox1.Items.Add("Programs: " + univ[3].programs);
listBox1.Items.Add("Tuition: $" + univ[3].tuition);
listBox1.Items.Add("Residence: $" + univ[3].residence);
}
else if (comboBox1.SelectedIndex == 4)
{
listBox1.Items.Clear();
pictureBox1.Image = Properties.Resources._5;
listBox1.Items.Add("Province: " + univ[4].prov);
listBox1.Items.Add("City: " + univ[4].city);
listBox1.Items.Add("Population: " + univ[4].population);
listBox1.Items.Add("Programs: " + univ[4].programs);
listBox1.Items.Add("Tuition: $" + univ[4].tuition);
listBox1.Items.Add("Residence: $" + univ[4].residence);
}
else
{
pictureBox1.Image = Properties.Resources.noimage;
listBox1.Items.Clear();
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label9_Click(object sender, EventArgs e)
{
}
private void label8_Click(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void label6_Click(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void textBox8_TextChanged(object sender, EventArgs e)
{
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void AddButton_Click(object sender, EventArgs e)
{
int u = 4;
int p = 4;
int c = 4;
int pop = 4;
int pro = 4;
int t = 4;
int r = 4;
univ[u+1].uni = textBox1.Text;
univ[p + 1].prov = textBox2.Text ;
univ[c + 1].city = textBox3.Text ;
univ[pop + 1].population = textBox4.Text ;
univ[pro + 1].programs = textBox5.Text;
univ[t + 1].tuition = textBox6.Text;
univ[r + 1].residence = textBox7.Text ;
StreamWriter sw = new StreamWriter("Universities.txt", true);
String line;
line = Console.ReadLine();
sw.WriteLine(univ[u + 1].uni + ", " + univ[p + 1].prov + ", " + univ[c + 1].city + ", " + univ[pop + 1].population + "," + univ[pro + 1].programs
+ ", " + univ[t + 1].tuition + "," + univ[r + 1].residence + ",");
MessageBox.Show("A University has been added.");
sw.Close();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("There are " + comboBox1.Items.Count + " universities.");
}
}
}
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
//your code goes here
string[] sPlit = line.Split(',');
univ[i].uni = sPlit[0];
univ[i].prov = sPlit[1];
univ[i].city = sPlit[2];
univ[i].population = sPlit[3];
univ[i].programs = sPlit[4];
univ[i].tuition = sPlit[5];
univ[i].residence = sPlit[6];
comboBox1.Items.Add(univ[i].uni);
}
}
}
catch (Exception p) //catches errors
{
Console.WriteLine("Exception: " + p.Message);
}
finally //final statement before closing
{
Console.WriteLine("Executing finally block.");
}
Hope Helps
Env: C#, VStudio 2013, 4.5 Framework, Winforms
Goal : Insert, inside a Treeview, the content of a folder (Sub folder + files) so that user can select those needed. Display a progressbar that show the progress of loading the files and folders in the TreeView.
What i've done so far : Everything in my goal but ...
Error: "This BackgroundWorker is currently busy and cannot run multiple tasks concurrently". I get this error sometimes when I go use other apps while my application is running.
My code :
void backgroundWorkerTreeView_DoWork(object sender, DoWorkEventArgs e)
{
var progress = (((float)(int)e.Argument / (float)totalFilesInTN) * 100);
var value = (int)Math.Round((float)progress);
backgroundWorkerTreeView.ReportProgress(value, e.Argument.ToString());
}
void backgroundWorkerTreeView_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
stStripBarMain.Value = e.ProgressPercentage;
toolStripStatusLabelPrct.Text = " Loading " + e.UserState + " of " + totalFilesInTN;
}
void backgroundWorkerTreeView_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do the code when bgv completes its work
}
private void ListDirectory(TreeView treeView, string path)
{
try
{
treeView.Nodes.Clear();
if (path != "")
{
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo, 0));
}
}
catch (Exception e)
{
txtLog.Text = txtLog.Text + "[" + DateTime.Now + "] " + e.Message + "\r\n";
}
}
private TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo, int indice)
{
var directoryNode = new TreeNode(directoryInfo.Name);
foreach (var directory in directoryInfo.GetDirectories())
{
if ((directory.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
{
directoryNode.Nodes.Add(CreateDirectoryNode(directory, indice));
}
}
foreach (var file in directoryInfo.GetFiles())
{
if ((IsNullOrEmpty(ext)) ||
(Array.IndexOf(ext, Path.GetExtension(file.Name.ToLowerInvariant())) >= 0))
{
if ((GetTriggerEvent(file.FullName).Contains(txtParamEvent.Text)) || (txtParamEvent.Text == ""))
{
indice++;
backgroundWorkerTreeView.RunWorkerAsync(indice);
TreeNode newTN = new TreeNode();
newTN.Text = file.Name + #" (" + GetTriggerEvent(file.FullName) + #")";
newTN.Name = file.FullName;
directoryNode.Nodes.Add(newTN);
newTN.Tag = "msg";
}
}
Application.DoEvents();
}
return directoryNode;
}
Thanks for the help
Richard
How do I print specified rows out to a file from a DataGridView?
Also how can I print out certain columns?
This is what I have been trying to work with.. but it is not working..:
private void saveButton_Click(object sender, EventArgs e)
{
saveFile1.DefaultExt = "*.txt";
saveFile1.Filter = ".txt Files|*.txt|All Files (*.*)|*.*";
saveFile1.RestoreDirectory = true;
if (saveFile1.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFile1.FileName);
List<string> theList = new List<string>();
foreach (var line in theFinalDGV.Rows)
{
if (line.ToString().Contains("FUJI"))
richTextBox1.AppendText(line + "\n");
}
}
}
Can anyone help me in the right direction?
DataGridViewRow.ToString() only gives you the typename back, not the row content. You can use this extender to get the rowcontent ('ColumnName'):
public static class Extender {
public static string RowToString(this DataGridViewRow dgvr) {
string output = "";
DataGridView dgv = dgvr.DataGridView;
foreach (DataGridViewCell cell in dgvr.Cells) {
DataGridViewColumn col = cell.OwningColumn;
output += col.HeaderText + ":" + cell.Value.ToString() + ((dgv.Columns.IndexOf(col) < dgv.Columns.Count - 1) ? ", " : "");
}
return output;
}
}
if you only want the content of the row without the coulmn-headername use this (space separated):
public static class Extender {
public static string RowToString(this DataGridViewRow dgvr) {
string output = "";
foreach (DataGridViewCell cell in dgvr.Cells) {
output += cell.Value.ToString() + " ";
}
return output.TrimEnd();
}
}
your code will look like this:
class YourClass
{
private void saveButton_Click(object sender, EventArgs e)
{
saveFile1.DefaultExt = "*.txt";
saveFile1.Filter = ".txt Files|*.txt|All Files (*.*)|*.*";
saveFile1.RestoreDirectory = true;
if (saveFile1.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFile1.FileName);
List<string> theList = new List<string>();
foreach (var line in theFinalDGV.Rows)
{
string linecontent = line.RowToString();
if (linecontent.Contains("FUJI"))
richTextBox1.AppendText(linecontent + "\n");
}
}
}
}
public static class Extender {
public static string RowToString(this DataGridViewRow dgvr) {
string output = "";
DataGridView dgv = dgvr.DataGridView;
foreach (DataGridViewCell cell in dgvr.Cells) {
DataGridViewColumn col = cell.OwningColumn;
output += col.HeaderText + ":" + cell.Value.ToString() + ((dgv.Columns.IndexOf(col) < dgv.Columns.Count - 1) ? ", " : "");
}
return output;
}
}