I've a datagridview for display data from Text file. Then, i've a button that have function to delete content on Text file (return it to 0 bytes).
But why event execute (by clicking button), the datagrid doesn't refresh even using .refresh() function. Here's my code on button that deleting content of file text.
private void button1_Click(object sender, EventArgs e)
{
File.WriteAllText("Transaction.txt", String.Empty);
dataGridView1.Refresh();
}
PS : The datagridview would change (empty of course) only after re-launch Windows Form.
You will need BindingList class to bind data to your datagridview:
var _bindingList = new BindingList<string>();
And in your form constructor:
public MyForm
{
InitializeComponent();
myDataGridView.BindingSource = _bindingList;
}
Create a timer to monitor the change of file:
DateTime lastWriteTime = DateTime.Now
private void timer_tick(object sender, EventArgs e)
{
FileInfo f = new FileInfo("C:\\myFile.txt");
if ( lastWriteTime == f.LastWriteTime) return;
lastWriteTime = f.LastWriteTime;
UpdateBindingList();
}
private void UpdateBindingList()
{
_bindingList.Clear();
//then read the file and add items to _bindingList.
}
Related
I have a TextBox, a Button, and a Combobox
When I click the Button, I want the text in Textbox to be added to the Combobox Items
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Add(textBox1.Text);
}
My form until open. This text shows in the Combobox, but when I close the Form and open it again the text is not longer shown in the Combobox.
I want to save the text to the Collection Items of the Combobox. I don't want to use a database.
As others have mentioned in the comments, you need to understand and decide where you wish to store your values.
For the purpose of my example, I have created a simple text file to store these values. The code reads from the file and adds each line as an item into the ComboBox.
private void Form1_Load(object sender, EventArgs e)
{
// Read items from file into a string array
string[] items = System.IO.File.ReadAllLines(#"D:\ComboBoxValues.txt");
// Add items to the comobobox when opening the form
comboBox1.Items.AddRange(items);
}
private void button1_Click(object sender, EventArgs e)
{
// Add your new value to the combobox
comboBox1.Items.Add(textBox1.Text);
// Put all existing comobo box items into a string array
string[] items = comboBox1.Items.OfType<string>().ToArray();
// Save the array of items to a text file (this will not append, it will re-write the file)
System.IO.File.WriteAllLines(#"D:\ComboBoxValues.txt", items);
}
This may not be the most elegant way of going about it, but from the point of providing you an understanding - this should be more than sufficient.
if you don't like to use File System, you can use Preferences(but it's not recommendable to use preference to memorize large values), check this link to see how create a new setting
private void Form1_Load(object sender, EventArgs e)
{
string[] strItems = Properties.Settings.Default.items.Split(", ");
for(int i = 0; i < strItems.length; i++) {
comboBox1.Items.Add(strItems[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
//add your new value to the combobox
comboBox1.Items.Add(textBox1.Text);
//put all existing combo box items into a string array
string[] items = comboBox1.Items.OfType<string>().ToArray();
for(int i = 0; i < items.length; i++) {
//I assumed you had an items key in your settings
if(i == items.length - 1) {
Properties.Settings.Default.items += value;
} else {
Properties.Settings.Default.items += value + ", ";
}
}
//then you should to save your settings
Properties.Settings.Default.Save();
}
I've been looking for a solution for days now.
Currently have 2 Forms. Main Form has multiple buttons, lets say (1-10).
All buttons will open up my 2nd Form (say I press Button 4). On my 2nd Form I have a ComboBox with different names and a confirm button. When I choose a name from the ComboBox, then press the confirm button.
I want the name selected in the ComboBox to be displayed as the new button text from my Main form (So name3 from Form 2 ComboBox will replace Button text (Button 4) on Main Form).
Any suggestions on how I can achieve this?
I can get the text from ComboBox to Main Form into a Label or a Button of my choosing, but I can't do it from the pressed button on Main Form which opened Form 2.
I've tried changing the button pressed on Main Form to a buttonTemp name, then letting the text from ComboBox change buttonTemp text, but it's coming up as it doesn't exist on Form 2.
Form 1 code:
public void b1111_Click(object sender, EventArgs e)
{
b1111.BackColor = Color.Red;
buttonTemp.Name = "bTemp2";
b1111.Name = "buttonTemp";
Classroom f4 = new Classroom();
f4.Show();
}
this is on Form 2:
private void button1_Click(object sender, EventArgs e)
{
temp1 = comboBox1.Text;
// trying to figure out the label text
foreach (Term1 Form1 in Application.OpenForms.OfType<Term1>())
{
Form1.buttonTemp.Text = comboBox1.Text;
}
this.Close();
}
Do not operate on the controls of other forms. Instead operate with values.
In your case when you finished and closed Form2 you can return a value back to the Form1 and update button text with a returned value.
In Form2 create public property which will be populated before you close Form2.
public string SelectedName { get; set; }
private void selectNameButton_Click(object sender, EventArgs e)
{
SelectedName = comboBox1.Text;
this.Close();
}
In Form1 use .ShowDialog() method to display form in modal form
public void openForm2Button_Click(object sender, EventArgs e)
{
openForm2Button.BackColor = Color.Red;
using (var form = new Classroom())
{
form.ShowDialog();
// next line will be execute after form2 closed
openForm2Button.Text = form.SelectedName; // update button text
}
}
Suggested by #Enigmativity in the comments:
// Form 2
public string SelectedName => comboBox1.Text;
private void selectNameButton_Click(object sender, EventArgs e)
{
this.Close();
}
// Form 1 remains same
There is many ways to get your goal.
I hope you try to use event.
You can make your own event as below.
private void Form1_Load(object sender, EventArgs e)
{
//define listen event from custom event handler
_form2.OnUserSelectNewText += new Form2.TextChangeHappen(_form2_OnUserSelectNewText);
}
When you have member variable for remember which button clicked by user.
private Control activeControl = null;
and you can get text that user's choice from your custom event at Form2.
//to make simple code, centralize all buttons event to here.
private void button_Click(object sender, EventArgs e)
{
//to remeber which button is clicked.
activeControl = (Button)sender;
_form2.ShowDialog();
}
and then you just change text of "activeControl".
private void _form2_OnUserSelectNewText(string strText)
{
activeControl.Text = strText;
}
please refer this, how to make custom event with delegate.
public partial class Form2 : Form
{
//you can expand your own custom event, string strText can be Control, DataSet, etc
public delegate void TextChangeHappen(string strText); //my custom delegate
public event TextChangeHappen OnUserSelectNewText; //my custom event
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// to prevent null ref exception, if there is no event handler.
if (OnUserSelectNewText != null)
{
OnUserSelectNewText(this.comboBox1.Text);
}
this.Close();
}
}
I have a form called ListaDeAlunos with a DataGridView on it.
When I double click on any cell, I want to open a form called Alunos for the selected row of the DataGridView on the form ListaDeAlunos, so I can edit the record. I almost got it to work, but the form Alunos does not show the right record when it opens.
Here's what I did so far:
On the source form I created a class called Variables
and in that class I created a public static string called RecordName
class Variables
{
public static string RecordName;
}
On the source form I created a CellDoubleClick event:
private void tbl_alunosDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
Form Alunos = new Alunos();
Alunos.MdiParent = this.MdiParent;
Alunos.Show();
Variables.RecordName = this.tbl_alunosDataGridView.CurrentRow.Cells[1].Value.ToString();
}
On the second form (the one that will open in the DoubleClick event), I have the following code on the Form_Load event:
private void Alunos_Load(object sender, EventArgs e)
{
this.tbl_alunosBindingSource.Filter = string.Format("Nome LIKE '{0}%'", Variables.RecordName);
}
Any ideas on how to fix this? It's almost working!
PROBLEM SOLVED !!!
All I had to do was to put the last line of code on top. Simple.
private void tbl_alunosDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{ Variables.RecordName = this.tbl_alunosDataGridView.CurrentRow.Cells[1].Value.ToString();
Form Alunos = new Alunos();
Alunos.MdiParent = this.MdiParent;
Alunos.Show();
}
I have a datagridview in my C# application and the user should only be able to click on full rows. So I set the SelectionMode to FullRowSelect.
But now I want to have an Event which is fired when the user double clicks on a row. I want to have the row number in a MessageBox.
I tried the following:
this.roomDataGridView.CellContentDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.roomDataGridView_CellCont entDoubleClick);
private void roomDataGridView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(e.RowIndex.ToString());
}
Unforunately nothing happens. What am I doing wrong?
In CellContentDoubleClick event fires only when double clicking on cell's content. I used this and works:
private void dgvUserList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(e.RowIndex.ToString());
}
Don't manually edit the .designer files in visual studio that usually leads to headaches. Instead either specify it in the properties section of your DataGridRow which should be contained within a DataGrid element. Or if you just want VS to do it for you find the double click event within the properties page->events (little lightning bolt icon) and double click the text area where you would enter a function name for that event.
This link should help
http://msdn.microsoft.com/en-us/library/6w2tb12s(v=vs.90).aspx
You get the index number of the row in the datagridview using northwind database employees tables as an example:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'nORTHWNDDataSet.Employees' table. You can move, or remove it, as needed.
this.employeesTableAdapter.Fill(this.nORTHWNDDataSet.Employees);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var dataIndexNo = dataGridView1.Rows[e.RowIndex].Index.ToString();
string cellValue = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
MessageBox.Show("The row index = " + dataIndexNo.ToString() + " and the row data in second column is: "
+ cellValue.ToString());
}
}
}
the result will show you index number of record and the contents of the second table column in datagridview:
This will work, make sure your control Event is assigned to this code, it has probably been lost, I also noticed that Double click will only work if the cell is not empty. Try double clicking on a cell with content, don't mess with the designer
private void dgvReport_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//do something
}
I think you are looking for this: RowHeaderMouseDoubleClick event
private void DgwModificar_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
...
}
to get the row index:
int indice = e.RowIndex
you can do this by : CellDoubleClick Event
this is code.
private void datagridview1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(e.RowIndex.ToString());
}
For your purpose, there is a default event when the row header is double-clicked. Check the following code,
private void dgvCustom_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
//Your code goes here
}
So I have an objectlistview (actually a treelistview). I want to be able to drag an item from this onto a richtextbox, and have it insert a property of the dragged item (in this case Default_Heirarchy_ID)
The TreeListView's objectmodel is a List<T> of a class called SpecItem.
This is what I have so far:
public frmAutospecEditor(SpecItem siThis_, List<SpecItem> lstStock_)
{
InitializeComponent();
txtFormula.DragEnter += new DragEventHandler(txtFormula_DragEnter);
txtFormula.DragDrop += new DragEventHandler(txtFormula_DragDrop);
...
}
void txtFormula_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void tlvSpecItem_ItemDrag(object sender, ItemDragEventArgs e)
{
int intID = ((SpecItem)tlvSpecItem.GetItem(tlvSpecItem.SelectedIndex).RowObject).Default_Heirarchy_ID ??0;
DoDragDrop(intID, DragDropEffects.Copy);
}
private void txtFormula_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
object objID = e.Data.GetData(typeof(String));
//this is where it goes wrong - no matter what I try to do with this, it
//always returns either null, or the text displayed for that item in the TreeListView,
//NOT the ID as I want it to.
string strID = (string)objID;
txtFormula.Text = strID;
}
Where am I going wrong?
Cheers
The Drag is the control you want to take data from (your OLV).
The Drop is the destination control (your textbox). So:
Set the IsSimpleDragSource property of your OLV to true.
In the textbox set AllowDrop property to true. Then handle the DragEnter event of your textbox and use the DragEventArgs param.
Handle the ModelDropped event:
private void yourOlv_ModelDropped(object sender, ModelDropEventArgs e)
{
// If they didn't drop on anything, then don't do anything
if (e.TargetModel == null) return;
// Use the dropped data:
// ((SpecItem)e.TargetModel)
// foreach (SpecItem si in e.SourceModels) ...
// e.RefreshObjects();
}
Read more: http://objectlistview.sourceforge.net/cs/dragdrop.html#ixzz1lEt7LoGr