I have made a method so that when you click on Browse From File the openDialogBox appear. But it does not . What is wrong ?
This is the method that I made to Open the OpenFileDialog:
public void Lista()
{
string[] col2 = new string[dataGridView1.Rows.Count];
for (int i = 0; i < dataGridView1.Rows.Count; i++)
if (col2[i] == "Browse From File...")
{
DialogResult result2 = openFileDialog2.ShowDialog();
if (result2 == DialogResult.OK)
{
// filename = openFileDialog1.FileName;
}
}
}
This is the method where I call the method Lista.
private void button1_Click(object sender, EventArgs e)
{
// opens window **BROWSE**
openFileDialog1.Title = "Choose File CSV ";
string filename = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog1.FileName;
textBox1.Text = filename;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(textBox1.Text);
stringforData = file.ReadLine();
while ((line = file.ReadLine()) != null)
{
//read inside the table
fileList.Add(line.Split(';'));
}
file.Close();
this.ToDataGrid();
this.Lista();
}
}
DataGridView by only having one editing control for all the rows. Here's how I handled a similar situation, First try a delegate to the EditControlShowing event
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OpenFileDialog ofd = new OpenFileDialog();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("ID", "Product ID");
DataGridViewComboBoxColumn comboxboxCol = new DataGridViewComboBoxColumn();
comboxboxCol.HeaderText = "Type";
comboxboxCol.Items.Add("Obj1");
comboxboxCol.Items.Add("Obj2");
comboxboxCol.Items.Add("Obj3");
dataGridView1.Columns.Add(comboxboxCol);
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(Grid_EditingControlShowing);
}
void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
// the event to handle combo changes
EventHandler comboDelegate = new EventHandler(
(cbSender, args) =>
{
ofd.ShowDialog();
});
// register the event with the editing control
combo.SelectedValueChanged += comboDelegate;
}
}
}
}
Hope this will solve your Issue
Related
I got an issue with the event-handling in my class:
public partial class BadFiles : Form
{
private DataTable dt = new DataTable();
private string oldCellValue = string.Empty;
public BadFiles()
{
InitializeComponent();
dataGridBadFiles.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
Closing += new CancelEventHandler(BadFiles_Closing);
dataGridBadFiles.CellBeginEdit += new DataGridViewCellCancelEventHandler(BadFiles_CellBeginEdit);
dataGridBadFiles.CellValueChanged += new DataGridViewCellEventHandler(BadFiles_CellValueChanged);
dataGridBadFiles.CellValidating += new DataGridViewCellValidatingEventHandler(BadFiles_CellValidating);
dt.Columns.Add("Files");
for (int i = 0; i < GlobalVars.BadFileNames.Count; i++)
{
dt.Rows.Add(Path.GetFileName(GlobalVars.BadFileNames[i]));
}
dataGridBadFiles.DataSource = dt;
}
private void BadFiles_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
oldCellValue = dataGridBadFiles[e.ColumnIndex, e.RowIndex].Value.ToString();
}
private void BadFiles_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (string.IsNullOrEmpty(e.ToString()) == true || (FileTools.CheckFileName(e.ToString()) == false))
{
e.Cancel = true;
dataGridBadFiles[e.ColumnIndex, e.RowIndex].Value = oldCellValue;
}
}
private void BadFiles_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
var newCellValue = dataGridBadFiles[e.ColumnIndex, e.RowIndex].Value.ToString();
if (FileTools.CheckFileName(newCellValue) == true)
{
var m = new string[]
{
oldCellValue,
newCellValue
};
MessageBox.Show(string.Join(Environment.NewLine, m));
}
else
{
newCellValue = oldCellValue;
MessageBox.Show("Bad Value!");
}
}
private void BadFiles_Closing(object sender, CancelEventArgs e)
{
if(FileTools.CheckFileFolder(GlobalVars.DataInput).Count != 0)
{
e.Cancel = true;
MessageBox.Show("Please rename all files in the list!", "Rename Files", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
The CellValidating event doesn't fire/work, so i tested something else with the CellValueChanged event but that isn't working either. The class shows a Form with a GridView filled from a list with bad filenames. Those filenames must be renamed from the user with a check if the new filenames are OK before changing them. The problem is that the filename checking doesn't work because of the events not firing when supposed to.
I have a code that read in a richtextbox the last row from a txt file.
What I want to introduce now is a refresh button with something like a text box.
I want to put it so user can put the number on the form that means minutes for the code and then user press the button refresh and the program will refresh every ... minutes. The program just call last file opened with open file dialog, refresh it on richtextbox every ... minutes.
Here is what I did to refresh just when you press the button refresh (maybe for implement it as I want I should put on the form another button and a text box?):
private string thePath;
public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
{
using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
thePath = ofd.FileName;
Refresh();
}
}
}
private void Refresh()
{
using (StreamReader rd = new StreamReader(thePath))
{
string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ReaderRichTxtBox.Text = lines[lines.Length - 1];
}
}
private void RefreshBtn_Click(object sender, EventArgs e)
{
Refresh();
}
How should the code be?
Thank you for help.
You should use some kind of Timer.
For example, you can declare a private System.Windows.Forms.Timer refreshtimer and instatiate it at the button click.
Assuming the textbox name is TextBox1, the code should look like this:
private System.Windows.Forms.Timer refreshtimer;
private string thePath;
public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
{
using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
thePath = ofd.FileName;
Refresh();
}
}
}
private void Refresh()
{
using (StreamReader rd = new StreamReader(thePath))
{
string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ReaderRichTxtBox.Text = lines[lines.Length - 1];
}
}
private void RefreshBtn_Click(object sender, EventArgs e)
{
refreshtimer = new System.Windows.Forms.Timer();
refreshtimer.Tick += new EventHandler(timer_Tick);
refreshtimer.Interval = Convert.ToInt32(TextBox1.Text) * 60000; //60000 is one minute
refreshtimer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
Refresh();
}
At the refresh button click I set the interval to the value of the TextBox (the interval is set in miliseconds, that is why I have multiplied by 60000).
I suggest you put the intialization of the timer in the constructor of the class.
Ask me more if you have any question and I will edit my answer.
public partial class TextReaderForm : Form
{
public TextReaderForm()
{
InitializeComponent();
}
private System.Windows.Forms.Timer refreshtimer;
private string thePath;
public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
{
using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
//using (StreamReader rd = new StreamReader(ofd.FileName))
{
//ReaderRichTxtBox.Text = await rd.ReadToEndAsync();
//string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
//ReaderRichTxtBox.Text = lines[lines.Length - 1];
thePath = ofd.FileName;
Refresh();
}
}
}
}
private void Refresh()
{
using (StreamReader rd = new StreamReader(thePath))
{
string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ReaderRichTxtBox.Text = lines[lines.Length - 1];
}
}
private void RefreshBtn_Click(object sender, EventArgs e)
{
Refresh();
}
private void RefreshTimerBtn_Click(object sender, EventArgs e)
{
refreshtimer = new System.Windows.Forms.Timer();
refreshtimer.Tick += new EventHandler(timer_Tick);
refreshtimer.Interval = Convert.ToInt32(RefreshTimerTxtBox.Text) * 60000; //60000 is one minute
timer1.Start();
}
void timer_Tick(object sender, EventArgs e)
{
Refresh();
}
}
I am trying to transfer the data entered in the TextBoxes to gridcontrol. There is no problem when I write to the text manually, but I have a button on the grid, but there is a button and the path of the selected file is transferred to the text. Why would that be? How can I solve it?
I'd appreciate it if you helped.
Thank you.
public frmYazdir(TblBilgi tbl)
{
InitializeComponent();
db = new DbEntities1();
if (tbl != null)
{
tblBilgiBindingSource.DataSource = tbl;
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog DosyaYukle = new OpenFileDialog();
DosyaYukle.Filter = "REPX Dosyaları(*repx.*) | *.repx*";
if (DosyaYukle.ShowDialog() == DialogResult.OK)
{
filename = DosyaYukle.FileName;
textBox1.Text = filename;
if (tbl != null)
{
db.TblBilgi.Attach(tblBilgiBindingSource.DataSource as TblBilgi);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
db.SaveChanges();
MessageBox.Show("Kaydedildi.");
}
public frmYazdir(TblBilgi tbl)
{
InitializeComponent();
db = new DbEntities1();
if (tbl != null)
{
tblBilgiBindingSource.DataSource = tbl;
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog DosyaYukle = new OpenFileDialog();
DosyaYukle.Filter = "REPX Dosyaları(*repx.*) | *.repx*";
if (DosyaYukle.ShowDialog() == DialogResult.OK)
{
filename = DosyaYukle.FileName;
textBox1.Text = filename;
if (tbl != null)
{
db.TblBilgi.Attach(tblBilgiBindingSource.DataSource as TblBilgi);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
db.SaveChanges();
MessageBox.Show("Kaydedildi.");
}
I have a windows form that reads strings from a file and shows them all in a textbox when I press a button.
private void buttonTxt_Click(object sender, EventArgs e)
{
string[] Test = File.ReadAllLines("C:\\testfile.txt");
for (int i = 0; i < testfile.Length; i++)
{
TextBox.Text += testfile[i];
}
}
I'd like to make two radio buttons. So that first button lets my program work the way I described (by default) AND second radio button makes it work vice versa -- so that I could write in a textbox myself and when I press a button it writes a new line to the same file. Is there a way to do it?
Simply add an if statement in this event handler and implement both sending and receiving the data. Done. Sample in principle:
private const string FilePath = #"C:\testfile.txt";
private void buttonTxt_Click(object sender, EventArgs e)
{
if (radioReadMode.Checked) // check which radio button is selected
{ // read mode
string[] Test = File.ReadAllLines(FilePath);
for (int i = 0; i < testfile.Length; i++)
TextBox.Text += testfile[i];
}
else
{ // write mode
File.WriteAllText(FilePath, TextBox.Text);
}
}
I believe this is what you might be looking for. If radio button 1 is checked then if the file exists it will read that file and put it into a textbox in the form. If you switch to radio button 2. You can type in the text box and then when you press the button it will append it to the file.
public partial class Form1 : Form
{
System.IO.StreamReader sr;
System.IO.StreamWriter sw;
public Form1()
{
InitializeComponent();
radioButton1.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sr = new System.IO.StreamReader("C:\\testfile.txt");
while (!sr.EndOfStream)
{
textBox1.Text += sr.ReadLine() + "\r\n";
}
}
finally
{
sr.Close();
sr.Dispose();
}
}
}
if (radioButton2.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sw = new System.IO.StreamWriter("C:\\testfile.txt", true);
string result = textBox1.Text;
string[] lststr = result.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in lststr)
{
sw.WriteLine(s);
}
}
finally
{
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = true;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = false;
}
}
Yes, there's a way. Just add another button to your form and inside read the text from the text box this way:
var textBoxContent = TextBox.Text;
and save it to your file this way
File.WriteAllText("C:\\testfile.txt", textBoxContent);
Note: I recommend getting the path to your file into a variable
I have a question about the opfiledialog function within c#. When i dont select a file with openfiledialog it put's a text automaticly in my textbox. That text will be "filedialog1". What can i do to fix this.
using System;
using System.Windows.Forms;
using System.IO;
namespace Flashloader
{
public partial class NewApplication : Form
{
private toepassinginifile _toepassinginifile;
private controllerinifile _controllerinifile;
//private controllerinifile _controlIniFile;
public NewApplication(toepassinginifile iniFile)
{
_controllerinifile = new controllerinifile();
_toepassinginifile = iniFile;
InitializeComponent();
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
public bool Run()
{
var result = ShowDialog();
return result == System.Windows.Forms.DialogResult.OK;
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
}
private void button3_Click(object sender, EventArgs e)
{
Toepassing toepassing = new Toepassing();
toepassing.Name = nameBox.Text;
toepassing.Controller = (Flashloader.Controller)controllerComboBox.SelectedItem;
toepassing.TabTip = descBox.Text;
toepassing.Lastfile = openFileDialog1.FileName;
fileBox.Text = openFileDialog1.FileName;
if (nameBox.Text == "")
MessageBox.Show("You haven't assigned a Name");
else if (controllerComboBox.Text == "")
MessageBox.Show("You haven't assigned a Controller");
else if (descBox.Text == "")
MessageBox.Show("You haven't assigned a Desciption");
else if (fileBox.Text == "")
MessageBox.Show("You haven't assigned a Applicationfile");
_toepassinginifile.ToePassingen.Add(toepassing);
_toepassinginifile.Save(toepassing);
MessageBox.Show("Save Succesfull");
DialogResult = DialogResult.OK;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
var newcontroller = new Newcontroller(_controllerinifile);
newcontroller.ShowDialog();
controllerComboBox.DataSource = null;
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
}
}
Thanks all for the help
private void button3_Click(object sender, EventArgs e)
{
toepassing.Lastfile = openFileDialog1.FileName;// Dont do this
fileBox.Text = openFileDialog1.FileName; //or this
Its unclear to me why you are holding onto an Open file dialog I would personally do the following
using(OpenFileDialog ofd = new OpenFileDialog())
{
if(ofd.ShowDialog() == DialogResult.OK)
{
classStringVariable = ofd.FileName;
fileBox.Text = ofd.FileName;
}
}
Then in button 3
toepassing.LastFile = classStringVariable ;
fileBox.Text = classStringVariable ;
When you use the Form Designer to add an OpenFileDialog control on you form, the designer assigns at the property FileName the value openFileDialog1.
I suppose you have set something as the initial value for the property FileName. Then in button_click3 you have no mean to check for the DialogResult and thus you get inconditionally this default back.
Fix it removing this default from the designer FileName property
Just add openFileDialog1.FileName= ""; before you show the dialog.
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileName != "")
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
In your button3_Click event you're checking for an empty string file name anyways, so they would get the correct error message and they wouldn't have some weird arbitrary default name show up when they open the dialog.