I am developing a windows forms application which uses OpenFileDialog to select files and drop it to a ListView.
The user should not be able to add same file to the listview twice. This should NOT happen:
How can this be done??
Have you tried checking if the listview contains the file before adding a new one?
The openfiledialog lets you filter by extension, but not by file name so you need to process the user selection after it closes. Perhaps showing a message dialog to tell the user that they selected a duplicate would be the best way to handle the invalid selection.
Try out this code.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var file = openFileDialog1.FileName;
if (listView1.FindItemWithText(file) == null)
listView1.Items.Add(file);
}
You can also add else with a message box informing user about choosing a duplicate file.
Check against existing entries.
var txt = comboBox1.Text;
if (!listView1.Items.ContainsKey(txt))
{
lvi.Text = txt;
// this is the key that ContainsKey uses. you might want to use the value
// of the ComboBox or something else, depending the combobox is freetext
// or regarding your scenario.
lvi.Name = txt;
lvi.SubItems.Add("");
lvi.SubItems.Add("");
lvi.SubItems.Add("");
lvi.SubItems.Add("");
listView1.Items.Add(lvi);
}
How prevent duplicate items listView C#
Related
I have tried to get an answer to this but so far no help has been able to do what I want it to.
I have this piece of code, which is meant to look at the selected row and output it's columns into the corresponding text boxes.
private void DataGridView01_SelectionChanged(object sender, EventArgs e)
{
if (DataGridView01.SelectedRows.Count > 0)
{
personIDTextBox.Text = DataGridView01.SelectedRows[0].Cells[0].Value.ToString();
comboBox1.Text = DataGridView01.SelectedRows[0].Cells[1].Value.ToString();
Txt_FirstName.Text = DataGridView01.SelectedRows[0].Cells[2].Value.ToString();
mIDDLENAMETextBox.Text = DataGridView01.SelectedRows[0].Cells[3].Value.ToString();
sURNAMETextBox.Text = DataGridView01.SelectedRows[0].Cells[4].Value.ToString();
cITYTextBox.Text = DataGridView01.SelectedRows[0].Cells[5].Value.ToString();
eMAILTextBox.Text = DataGridView01.SelectedRows[0].Cells[6].Value.ToString();
}
}
When I launch the program, I get no errors but it doesn't output the data into the textbox. Anyone know what I am doing wrong?
HOOKING UP EVENTS:
It is the most basic thing you need to learn to code in VS. In short it means that the event name, here DataGridView01_SelectionChanged is connected to the event. To do so one can either use code or one inserts it into the correct slot of the events pane of the property tab. Select the DataGridView, open the events pane (the one with the flash) and locate the SelectionChanged event! Here insert the name of the event and you are done.
(I only have the German versions of VS installed..)
The result is reflected in the form_designer.cs file and it is the same thing (in reverse) as double clicking that spot and then filling in the generated code stub..
Controls have many events; one is the default event and this can be generated by double clicking the control itself in the designer. But eventually you will need all 3 ways to generate and hook up the events, (as well as sometimes removing them.)
I use a slightly different approach when trying to get data from a datagridview.
Try doing personIDTextBox.Text = DataGridView01.SelectedCells[0].Value.ToString();
but instead of the event being on selection change, switch to CellClick and change the property of the the datagridview row selection property to full row select. after that you can change the SelectedCell[0] number to match whichever cell you want
If you want to display the datagridview selected rows into corresponding textboxes, fine the below steps ,
Step 1:
1. Change the DataGridView Selection mode to FullRowSelect in Datagridview property.
2. Create the cell click event in Data grid view using property.
enter image description here
3. Write the below code and test it, It may helpful
private void DataGridView01_CellClick(object sender,DataGridViewCellEventArgs e)
{
if (DataGridView01.Rows.Count > -1)
{
PersonIdTextBox.Text=DataGridView01.Rows[e.RowIndex].Cells[0].Value.ToString();
comboBox1.Text = DataGridView01.Rows[e.RowIndex].Cells[1].Value.ToString();
Txt_FirstName.Text = DataGridView01.Rows[e.RowIndex].Cells[2].Value.ToString();
mIDDLENAMETextBox.Text = DataGridView01.Rows[e.RowIndex].Cells[3].Value.ToString();
sURNAMETextBox.Text = DataGridView01.Rows[e.RowIndex].Cells[4].Value.ToString();
cITYTextBox.Text = DataGridView01.Rows[e.RowIndex].Cells[5].Value.ToString();
eMAILTextBox.Text = DataGridView01.Rows[e.RowIndex].Cells[6].Value.ToString();
}
}
I have been searching for DAYS for material explaining how to do this...
I have a code in WPF (C#) that loops through a collection of FrameworkElements. The objective is to save each of the FrameworkElements as separate images (gif files). The code is working currently and does in fact save all of the images I need.
However, the user has to manually click the "Save" button in the SaveFileDialog box for EACH element. There are over 100 elements. I want the code to Open the SaveFileDialog box and automatically "click" the "Save" button for the user throughout the loop (ie - for each element).
Here is the code currently...
foreach(FrameworkElement x in y)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = " ...blah...";
dlg.DefaultExt = "...blah..";
Nullable<bool> result = dlg.ShowDialog(); // (A)
string path = dlg.FileName;
int selectedFilterIndex = dlg.FilterIndex;
if(result == true) // (B)
{ ... then do all the rendering, cropping, etc.. .. }
}
I know that I can write some line in between the line containing "(A)" and "(B)" that will activate the "Save" button. I cannot find any examples online that eliminate the "if" statement.
I don't want my code to "wonder if this result will be true". I want the code to actually set the result to true regardless of anything else.
Any help is greatly appreciated.
So basically what I want is the user presses a browse button and a FolderBroswerDialog pops up. The user then selects a folder and the ViewList is then populated with all the images in that folder in Icon view. How can I do this? The code I currently have will select all the files from a folder and display them in the ListView, however there are no icons. How can I get icons?
Here is the code I currently have...
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog browsefolder = new FolderBrowserDialog();
if (browsefolder.ShowDialog() == DialogResult.OK)
{
listView1.Items.Clear();
string[] myfiles = Directory.GetFiles(folderPicker.SelectedPath);
foreach (string file in myfiles)
{
string fileName = Path.GetFileNameWithoutExtension(file);
ListViewItem myitem = new ListViewItem(fileName);
myitem.Tag = file;
listView1.Items.Add(myitem);
}
}
}
This is not so easy to do in an accurate and performant way. The quick and dirty way is to use Icon.ExtractAssociatedIcon() and add the returned icon to the ImageList associated with the list view. But you won't get the exact same icons you'd see in Explorer. That requires pinvoking SHGetFileInfo(), painful to do yourself but the code is easy to google.
An entirely different approach is to embed the Explorer window into your own form instead of using a ListView. With the major advantages that you'll get the exact same look and you'll automatically get the background thread that looks up icons while your program keeps responsive. With the disadvantage that this won't work for XP. The classes you need are part of the Windows API Code Pack.
I am working on Windows Form Application and have created a TextBox control and a Browse button control, so that user can select a folder through Button and show directory in TextBox.
I want to give a freedom to the user to paste a directory path directly into the TextBox. However, at the same, user must provide only a valid directory as a string/text in TextBox.
In addition, I want to disable editing this directory either by keyboard or any other possible way. The user will be able to paste a new valid directory anytime but can't edit it in the TextBox.
Is there any way to do this using C# at runtime?
Thanks.
If you set the textbox to ReadOnly then that stops editing the TextBox.
Then add an event for KeyDown you can capture if Ctrl + V is pressed and then action based on that using the Clipbboard class and if the directory is valid set the TextBox.Text.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V)
{
var clipboard = Clipboard.GetText();
if (Directory.Exists(clipboard))
textBox1.Text = clipboard;
}
}
I want to give a freedom to the user to paste a directory path
directly into the TextBox. However, at the same, user must provide
only a valid directory as a string/text in TextBox.
In addition, I want to disable editing this directory either by
keyboard or any other possible way. The user will be able to paste a
new valid directory anytime but can't edit it in the TextBox.
Isn't it contradictory ?
Why don't you use two text boxes then ? First for user to input/paste, with onchange event catching that calls a method that checks the directory's path is correct. If it is, the method copies it to the second text box, not editable, that is also linked to your directory browser.
You could handle the TextChanged event and check to see if the folder is valid and accessible there; if it's not, undo their change. This might not be practical if they can edit the textbox text, as it'll check to see if the folder exists after every keystroke and so typing anything new will be impossible. This might be how you want it to behave however!
To do the checking if the path is valid, I'd use Path.GetFullPath - pass it your textbox text and it'll throw an exception if the path doesn't exist/isn't valid/you don't have permission to access it.
If this feels a bit messy to you, instead of giving them the ability to edit the textbox, you could have a button that sets the text from the clipboard using Clipboard.GetText() and then performs your checks.
Thanks all for suggestions and answers.
Here is something that I did and worked like a charm for me.
I hope, this will help later for someone if face the same problem.
It is the modified version of the original code posted here by LukeHennerley. Thanks LukeHennerley for that.
private void txtBoxTargetDir_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V)
{
var clipboard = Clipboard.GetText();
if (Directory.Exists(clipboard))
{
txtBoxTargetDir.Clear();
txtBoxTargetDir.Text = clipboard;
txtBoxTargetDir.ReadOnly = true;
}
else
{
txtBoxTargetDir.Clear();
txtBoxTargetDir.Text = "It's not a valid directory. Please provide a valid directory.";
}
}
}
You will have to add this event in Form.Designer.cs first.
I am using wpf in c#.
Question 1: I created a wpf window. Is there a way to load the previous users entered fields of the form via a button click event?
Question 2: So after I load the field of the form, I would like to create a clear button to clear all the fields of the form. Is there a way to achieve this?
Thanks.
EDIT 1
I am currently struggling with XML serialization, trying to read up but i am still pretty lost. From what i know i am going to create a new class and i would have a "Save" button and "Load" button in my application. I have a few combo boxes, each one populated by some XML file already. I also have textboxes, checkboxes for them to fill up. So once users enters the form, i would like to have them to "save" the form entries and be able to "load" them whenever they wish. I have also studied the filebrowserdialog which will open an explorer for user to explore and save a copy of the old form in some directory but right now i only have this in my code:
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
}
this is far from what i require at the moment.
i think i'm pretty lost especially the part on creating new class for the combo box values. please guide me if possible. would also appreciate if you can guide me on text box and combo box values too. thanks.
this is how i populate the combo boxes:
public void PopulateDDLFromXMLFile()
{
DataSet ds = new DataSet();
ds.ReadXml("C:\\GUI\\buildermanageremail.xml");
DataView dv = ds.Tables["builder"].DefaultView;
DataView dw = ds.Tables["manager"].DefaultView;
dv.Sort = "value";
comboBox1.ItemsSource = dv; //Sets the collection of items from which to populate
comboBox2.ItemsSource = dw;
comboBox1.DisplayMemberPath = "value"; //Sets the path within an item to use for display
comboBox2.DisplayMemberPath = "value";
}
Yes sure its possible.. You may store per user entries in a database or temp file (Serialize) and show them in your text boxes when you load the form or as you mentioned you have a button to do that. Its similar to what you usually do when you show data from database on your form in Labels/TextBoxes or Gridview.
But to make it work you will need to save the user entries in the first place. You can either you can have a Button that allow user to save data or you can do so in Texthange/ LostFocus events of the controls.
If you don't need data to be persistent you can just store them in the variables and keep them in memory till the lifetime of the app.
For clearing the form a sample code will be like;
foreach(Control ctl in this.Controls)
{
TextBox tbx = ctl as TextBox;
if(tbx != null)
{
tbx.Text = String.Empty;
}
}
If you were to move all data out to a Model object (use MVVM to seperate these layers) bind all the controls to properties on the model, then you can simply serialize the model to a file to save and deserialize on load.
A clear button could simply create a new instance of the model, minimal code to write to achieve this.