Remove selected item from ListView from ImageFileCollectionViewModel - c#

I'm trying to remove the selected Item file from the list-view and also from the directory but I couldn't succeed. How can i remove this.?
string destination_dir = System.IO.Directory.GetCurrentDirectory() + #"./4x6";
public ImggLList()
{
InitializeComponent();
ListViewImage.Items.Clear();
DataContextChanged += OnDataContextChanged;
ImageFileCollectionViewModel ImagesViewModel = new ImageFileCollectionViewModel();
ImageFileControler.CompleteViewList(ImagesViewModel, destination_dir);
ListViewImage.DataContext = ImagesViewModel;
}
OnDataContextChanged
private ImageFileCollectionViewModel _currentDataContext = null;
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (_currentDataContext == DataContext) return;
if (_currentDataContext != null)
_currentDataContext.SelectedImageFileViewModels = null;
_currentDataContext = DataContext as ImageFileCollectionViewModel;
if (_currentDataContext != null)
_currentDataContext.SelectedImageFileViewModels = ListViewImage.SelectedItems;
}
Button Function:
private List<ImageFileViewModel> copyOfSelection;
private ImageFileCollectionViewModel imageFileCollection;
private void Delte_Photo_Click(object sender, RoutedEventArgs e)
{
copyOfSelection = imageFileCollection.SelectedImageFileViewModels.Cast<ImageFileViewModel>().ToList();
foreach (ImageFileViewModel ifvm in copyOfSelection)
{
copyOfSelection.Remove(ifvm);
File.Delete(destination_dir);
}
}
NullExeception Error:

for (int i = 0; i < copyOfSelection.Count; i++)
{
copyOfSelection.RemoveAt(i);
File.Delete(destination_dir);
}

Related

How to fix the drag and drop using dev express in c# after fetching data and setting tag property

enter image description here
namespace Implementer
{
public partial class MainForm : Form
{
#region intit and globals
public MainForm()
{
InitializeComponent();
DevExpress.XtraGrid.Views.Grid.GridView gridView = new DevExpress.XtraGrid.Views.Grid.GridView();
var transactions = new ObservableCollection<Item>();
for (int i = 0; i <= 100; i++)
{
transactions.Add(new Item { Content = "Item " + i });
}
grdTransactions.AllowDrop = true;
grdTransactions.DataSource = transactions;
dgmWf.AddingNewItem += (s, e) => transactions.Remove(e.Item.Tag as Item);
}
Point mouseDownLocation;
GridHitInfo gridHitInfo;
#endregion
#region events
public void Mainform_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'vA_ERP4_ADMINDataSet.SYSTEM_MODULES' table. You can move, or remove it, as needed.
//Project initiation
//Fill drop down for project list
cmbProject.SelectedIndex = 0;
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtResult = dataAccess.ExecuteQueryDataSet("select MODULE_CODE, MODULE_DESC from SYSTEM_MODULES where module_is_active=1").Tables[0];
cmbProject.DisplayMember = "MODULE_DESC";
cmbProject.ValueMember = "MODULE_CODE";
cmbProject.DataSource = dtResult;
}
private void cmbProject_SelectedIndexChanged(object sender, EventArgs e)
{
lblCurrentProject.Text = cmbProject.Text;
if (cmbProject.Text != null)
{
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtTransactions = dataAccess.ExecuteQueryDataSet("select sys_trans_id, sys_trans_desc1 from WF_SYSTEM_TRANS where MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
grdTransactions.DataSource = dtTransactions;
}
}
private void btnSalesInvoice_Click(object sender, EventArgs e)
{
int sysTransId = 1001;
FillTransactionDetails(sysTransId);
}
#endregion
#region drag drop
private void grdTransactions_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && CanStartDragDrop(e.Location))
{
StartDragDrop();
}
}
private void grdTransactions_MouseDown(object sender, MouseEventArgs e)
{
gridHitInfo = grdVTransactions.CalcHitInfo(e.Location);
mouseDownLocation = e.Location;
}
private void grdTransactions_MouseLeave(object sender, EventArgs e)
{
if (gridHitInfo != null)
gridHitInfo.View.ResetCursor();
gridHitInfo = null;
}
private bool CanStartDragDrop(Point location)
{
return gridHitInfo.InDataRow && (Math.Abs(location.X - mouseDownLocation.X) > 2 || Math.Abs(location.Y - mouseDownLocation.Y) > 2);
}
public void StartDragDrop()
{
var draggedRow = gridHitInfo.View.GetRow(gridHitInfo.RowHandle) as Item;
var tool = new FactoryItemTool(" ", () => " ", diagram => new DiagramShape(BasicShapes.Rectangle) { Content = draggedRow.Content, Tag = draggedRow }, new System.Windows.Size(150, 100), false);
dgmWf.Commands.Execute(DiagramCommandsBase.StartDragToolCommand, tool, null);
}
#endregion
#region function
private void FillTransactionDetails(int systemTransactionId)
{
//Fill document
//Fill steps
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable transactionDetails = dataAccess.ExecuteQueryDataSet("SELECT DOC_TYPE_DESC1 FROM WF_SYSTEM_TRANS_DT WHERE SYS_TRANS_ID=1001 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionDetails.Rows.Add();
grdDocuments.DataSource = transactionDetails;
grdDocuments.Columns["Details"].DisplayIndex = 2;
grdDocuments.Columns["Delete"].DisplayIndex = 2;
DataTable transactionSteps = dataAccess.ExecuteQueryDataSet("select WF_STEP_DESC1 from WF_STEPS where wf_id= 10101 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionSteps.Rows.Add();
grdSteps.DataSource = transactionSteps;
}
#endregion
}
public class Item
{
public string Content { get; set; }
}
}
I don't really know where is the mistake and have been looking at it for the past few days and searching for an answer but no luck so I'd be so happy if you could help me out. It was working without the data fetching. but after calling the data it doesn't work. drag it from the grid view and when it reaches the diagram control it would turn into a rectangle with a tag property of it's ID.. With regards to the connection string.. I created a global function to just call it on the main form.

Load JSON File to ListBox and TextBox C#

I'm working on a Windows Form Application. Textbox index can be saved and shown as in ListBox with this code:
private List<FunctionData> funcParamList = new List<FunctionData>();
...
private void addFuncButton_Click(object sender, EventArgs e)
{
FunctionData funcParams = new FunctionData();
funcParams.blabla1name = blabla1.Text;
funcParams.blabla2name = blabla2.Text;
...
if (funcParams.isValid())
{
funcParamList.Add(funcParams);
functionListBox.Items.Add(functionNameBox.Text);
}
Also I collect objects to TextBox again to edit (by clicking ListBox item) with the following code :
private void getParams(FunctionData data)
{
blabla1.Text = data.blabla1name;
blabla2.Text = data.blabla2name;
functionNameBox.Text = data.functionName;
return;
}
private void functionListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (functionListBox.SelectedItem == null) { return; }
foreach (var obj in funcParamList)
{
if (obj.functionName == functionListBox.SelectedItem.ToString())
{
getParams(obj);
}
}
}
And save them to file as JSON with:
private void saveFileButton_Click(object sender, EventArgs e)
{
fileName = fileNameBox.Text;
string jsonFunc = JsonConvert.SerializeObject(funcParamList);
System.IO.File.WriteAllText(#"<blablapath>\" + fileName + ".txt", jsonFunc);
}
There's 'functionName' object in JSON file that I can use it for showing on ListBox.
My question is: How can I load this file buy Native Load/Open File Dialog and show the objects in ListBox and can edit them again?
And here how I've tried to make it with the following code, but it doesn't work:
private void loadFileButton_Click(object sender, EventArgs e)
{
OpenFileDialog loadFileDialog = new OpenFileDialog();
...
if (loadFileDialog.ShowDialog() == DialogResult.OK)
{
string jsonFileName = loadFileDialog.FileName;
string jsonFile = File.ReadAllText(jsonFileName);
dynamic loadedFile = JsonConvert.DeserializeObject(jsonFile);
//if (functionListBox.SelectedItem == null) { return; }
foreach (var obj in loadedFile)
{
if (obj.functionName != null)
{
functionListBox.Items.Add(obj.functionName);
getParams(obj); // I get exception here
funcParamList.Add(loadedFile);
functionListBox.Refresh();
}
}
}
I've solved the problem by casting 'DeserializeObject' as List and it's done. Here the changes:
...
var loadedFile = JsonConvert.DeserializeObject<List<FunctionData>>(jsonFile);

ADD url in textbox to listbox in Windows Form Application c#

Iam new in programming.In windows Form application ,I want user can write a url in textbox and add (with button) in listbox as a favorite list,then user can click in listbox and then go to browser, finaly can save and open the list? whitout Microsoft Sql Database.I Need a source code.
textbox: (Enter your WebSite) : www.google.com
Button:ADD To List Box
Listbox:WWW.Google.com
Button :Save
Button :Open
You have to save the ListBox.Items as plain text file if not wanting to use database. Without binding, this simple problem becomes a little nasty if you start digging into writing it. Here is one of the solution you may need:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int lastIndex = -1;
bool suppressSelectedIndexChanged;
//Click event handler for buttonAdd
private void buttonAdd_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
suppressSelectedIndexChanged = true;
listBox1.SelectedIndex = listBox1.Items.Count - 1;
suppressSelectedIndexChanged = false;
}
//Click event handler for buttonRemove
private void buttonRemove_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndices.Count == 0) return;
int k = listBox1.SelectedIndices[0];
suppressSelectedIndexChanged = true;
for (int i = listBox1.SelectedIndices.Count - 1; i >= 0; i--)
listBox1.Items.RemoveAt(listBox1.SelectedIndices[i]);
suppressSelectedIndexChanged = false;
lastIndex = -1;
listBox1.SelectedIndex = k < listBox1.Items.Count ? k : listBox1.Items.Count - 1;
if (listBox1.Items.Count == 0) textBox1.Clear();
}
//Click event handler for buttonSave
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "URLs file|*.urls";
save.FileOk += (s, ev) =>
{
using (StreamWriter writer = File.CreateText(save.FileName))
{
foreach (object item in listBox1.Items)
{
writer.WriteLine(item.ToString());
}
}
};
save.ShowDialog();
}
//Click event handler for buttonOpen
private void buttonOpen_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "URLs file|*.urls";
open.FileOk += (s, ev) =>
{
listBox1.Items.Clear();
using (StreamReader reader = File.OpenText(open.FileName))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
};
open.ShowDialog();
}
//SelectedIndexChanged event handler for listBox1
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (suppressSelectedIndexChanged) return;
if (lastIndex > -1)
{
listBox1.Items[lastIndex] = textBox1.Text;
}
lastIndex = listBox1.SelectedIndex;
if (listBox1.SelectedIndex > -1)
textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();
}
//Click event handler for buttonVisit
private void buttonVisit_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem == null) return;
System.Diagnostics.Process.Start(listBox1.SelectedItem.ToString());
}
}
Here is the GUI screen shot for you to know which controls are needed:
private void btnAdd_Click(object sender, EventArgs e)
{
string _webstring = #"http://";
string _website = _webstring + textBox1.Text;
listBox1.Items.Add(_website);
using (StreamWriter w = File.AppendText("websites.txt"))
{
WriteLog(_website, w);
}
using (StreamReader r = File.OpenText("websites.txt"))
{
DisposeLog(r);
}
}
private void btnLaunch_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("iexplore.exe", listBox1.SelectedItem.ToString());
}
private void btnSave_Click(object sender, EventArgs e)
{
using (StreamWriter w = File.AppendText("websites.txt"))
{
foreach (string items in listBox1.Items)
{
WriteLog(items, w);
}
}
using (StreamReader r = File.OpenText("websites.txt"))
{
DisposeLog(r);
}
}
public static void WriteLog(string logMessage, TextWriter w)
{
w.WriteLine(logMessage, logMessage);
}
public static void DisposeLog(StreamReader r)
{
string line;
while ((line = r.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
private void btnRetrieve_Click(object sender, EventArgs e)
{
using (TextReader txtRead = File.OpenText("Websites.txt"))
{
string _text = "";
string[] _textArray = null;
while ((_text = txtRead.ReadLine()) != null)
{
_textArray = _text.Split('\t');
listBox1.Items.Add(txtRead.ReadLine());
}
txtRead.Close();
}
}
hope this helps.. thanks

Showing virtual keyboard when clicking on a textbox inside WebControl

I have created a virtual keyboard, the keyboard pops up for wpf textbox controls. How can I make the keyboard pops out when clicking on a textbox inside a web page?
the logic for displaying a textbox is given below:
static void TouchScreenKeyboardPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
FrameworkElement host = sender as FrameworkElement;
if (host != null)
{
host.GotFocus += new RoutedEventHandler(OnGotFocus);
host.LostFocus += new RoutedEventHandler(OnLostFocus);
}
}
static void OnGotFocus(object sender, RoutedEventArgs e)
{
Control host = sender as Control;
if (sender == typeof(TextBox))
{
_PreviousTextBoxBackgroundBrush = host.Background;
_PreviousTextBoxBorderBrush = host.BorderBrush;
_PreviousTextBoxBorderThickness = host.BorderThickness;
host.Background = Brushes.Yellow;
host.BorderBrush = Brushes.Red;
host.BorderThickness = new Thickness(4);
}
_CurrentControl = host;
if (_InstanceObject == null)
{
FrameworkElement ct = host;
while (true)
{
if (ct is Window)
{
((Window)ct).LocationChanged += new EventHandler(TouchScreenKeyboard_LocationChanged);
((Window)ct).Activated += new EventHandler(TouchScreenKeyboard_Activated);
((Window)ct).Deactivated += new EventHandler(TouchScreenKeyboard_Deactivated);
break;
}
if(ct.Parent != null)
ct = (FrameworkElement)ct.Parent;
}
_InstanceObject = new TouchScreenKeyboard();
_InstanceObject.AllowsTransparency = true;
_InstanceObject.WindowStyle = WindowStyle.None;
_InstanceObject.ShowInTaskbar = false;
_InstanceObject.ShowInTaskbar = false;
_InstanceObject.Topmost = true;
host.LayoutUpdated += new EventHandler(tb_LayoutUpdated);
}
}
static void TouchScreenKeyboard_Deactivated(object sender, EventArgs e)
{
if (_InstanceObject != null)
{
_InstanceObject.Topmost = false;
}
}
static void TouchScreenKeyboard_Activated(object sender, EventArgs e)
{
if (_InstanceObject != null)
{
_InstanceObject.Topmost = true;
}
}
static void TouchScreenKeyboard_LocationChanged(object sender, EventArgs e)
{
syncchild();
}
static void tb_LayoutUpdated(object sender, EventArgs e)
{
syncchild();
}
static void OnLostFocus(object sender, RoutedEventArgs e)
{
Control host = sender as Control;
host.Background = _PreviousTextBoxBackgroundBrush;
host.BorderBrush = _PreviousTextBoxBorderBrush;
host.BorderThickness = _PreviousTextBoxBorderThickness;
if (_InstanceObject != null)
{
_InstanceObject.Close();
_InstanceObject = null;
}
}
#endregion
}
private static void syncchild()
{
if (_CurrentControl != null && _InstanceObject != null)
{
Point virtualpoint = new Point(0, _CurrentControl.ActualHeight + 3);
Point Actualpoint = _CurrentControl.PointToScreen(virtualpoint);
if (WidthTouchKeyboard + Actualpoint.X > SystemParameters.VirtualScreenWidth)
{
double difference = WidthTouchKeyboard + Actualpoint.X - SystemParameters.VirtualScreenWidth;
_InstanceObject.Left = Actualpoint.X - difference;
}
else if (!(Actualpoint.X > 1))
{
_InstanceObject.Left = 1;
}
else
_InstanceObject.Left = Actualpoint.X;
_InstanceObject.Top = Actualpoint.Y;
_InstanceObject.Show();
}
}
private static void SetKeyInBrowser(string key)
{
var elementName = (((mshtml.HTMLDocument)(dom)).activeElement).id;
if (elementName != null)
{
var existingText = dom.getElementById(elementName).getAttribute("value");
if (existingText == null)
{
existingText = "";
}
//if it's a backspace.
if (isBackspace)
{
existingText = existingText.ToString().Remove(existingText.ToString().Length - 1);
dom.getElementById(elementName).setAttribute("value", existingText.ToString());
}
else if (key.Length != 0)
{
dom.getElementById(elementName).setAttribute("value", existingText.ToString() + key[key.Length - 1]);
}
}
isBackspace = false;
}
You need to use javascript for that. You need to know when that textfield is focused like this:
Check if focus is on a textfield
And then once the focused event is fired on JavaScript you should call your WPF function for showing the keyboard up. Here's useful hints:
How to programmaticaly check if a text input box inside a web page loaded in WPF Browser has focus?

objects in datagridview

Im adding objects to a datagridview ( only one kind) through a list
ej.
List<Material> mater = new List<Material>();
DataGridView dgvMAterial = new DataGridView();
dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
dgvMaterial.DataSource = mater;
But every time I click over the datagrid I get an indexoutofrangeexeption.
Can somone tell me why?
thanks
here is my whole code for the form
public partial class inicio : Form
{
private string ConnectionString = "Data Source=localhost\\sqlexpress;Initial Catalog=data.mdf;Integrated Security=SSPI;";
//private string ConnectionString = "Server=.\\SQLExpress;AttachDbFilename=|DataDirectory|\\data\\data_data.mdf.mdf; Database=data.mdf;Trusted_Connection=Yes;";
private ISessionFactory sessionFactory;
List<Material> mater = new List<Material>();
List<Salarios> salar = new List<Salarios>();
IBindingList mind = new BindingList<Salarios>();
Productos prod;
public inicio()
{
InitializeComponent();
sessionFactory = nhn.BusinessObjects.Initialize.CreateSessionFactory(ConnectionString);
dgvMaterial.DataSource = mater;
}
private void materialToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmMaterial material = new costeos.Catalogos.frmMaterial(ConnectionString);
material.ShowDialog(this);
material.Dispose();
}
private void salariosToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmSalarios salarios = new costeos.Catalogos.frmSalarios(ConnectionString);
salarios.ShowDialog(this);
salarios.Dispose();
}
private void agregarToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmAddRemuneraciones rem = new costeos.Catalogos.frmAddRemuneraciones(ConnectionString);
rem.ShowDialog(this);
rem.Dispose();
}
private void agregarToolStripMenuItem1_Click(object sender, EventArgs e)
{
Catalogos.frmAddAdmin adm = new costeos.Catalogos.frmAddAdmin(ConnectionString);
adm.ShowDialog(this);
adm.Dispose();
}
private void agregarToolStripMenuItem2_Click(object sender, EventArgs e)
{
Catalogos.frmAddInsumosInd insumos = new costeos.Catalogos.frmAddInsumosInd(ConnectionString);
insumos.ShowDialog(this);
insumos.Dispose();
}
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) || char.IsPunctuation(e.KeyChar) || char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
private void inicio_Load(object sender, EventArgs e)
{
LlenaCampos();
}
private void LlenaCampos()
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var mat = session.CreateCriteria(typeof(Material))
.List<Material>();
var sal = session.CreateCriteria(typeof(Salarios))
.List<Salarios>();
transaction.Commit();
cmbMaterial.DataSource = mat;
cmbMaterial.DisplayMember = "Nombre";
cmbSalarios.DataSource = sal;
cmbSalarios.DisplayMember = "Nombre";
cmbMIndirecta.DataSource = sal;
cmbMIndirecta.DisplayMember = "Nombre";
}
}
}
private void btnAddMaterial_Click(object sender, EventArgs e)
{
materialBindingSource.DataSource = null;
//dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
//dgvMaterial.DataSource = mater;
dgvMaterial.DataSource = materialBindingSource;
materialBindingSource.DataSource = mater;
materialBindingSource.ResetBindings(false);
}
private void button2_Click(object sender, EventArgs e)
{
dgvSalarios.DataSource = null;
salar.Add((Salarios)cmbSalarios.SelectedValue);
dgvSalarios.DataSource = salar;
}
private void button3_Click(object sender, EventArgs e)
{
dgvMIndirecta.DataSource = null;
mind.Add((Salarios)cmbMIndirecta.SelectedValue);
dgvMIndirecta.DataSource = mind;
}
private void button1_Click(object sender, EventArgs e)
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
if (prod == null)
{
prod = new Productos { CargasTurno = float.Parse(txtCargasTurno.Text), CavidadesMolde = int.Parse(txtCavidadesMolde.Text), Clave = txtClave.Text, Comentarios = txtComentarios.Text, MezclasTurno = float.Parse(txtMezclasTurno.Text), Moldes = int.Parse(txtMoldes.Text), Nombre = txtNombre.Text, Peso = float.Parse(txtPesoTotal.Text), TotalPza = int.Parse(txtPzasTotales.Text), Turnos = int.Parse(txtTurnos.Text) };
session.Save(prod);
transaction.Commit();
}
foreach (DataGridViewRow dr in dgvMaterial.Rows)
{
Material m = dr.DataBoundItem as Material;
m.Materiales
PMaterial mat = new PMaterial { Material = dr.DataBoundItem as Material, Cantidad = float.Parse(dr.Cells["Cantidad"].Value.ToString()), Fecha = DateTime.Now, Producto = prod };
session.Save(mat);
}
transaction.Commit();
session.Close();
}
}
}
}
}
That's probably not DGV problem, but with this combo box. Show us the code that fills combo box and sets its properties.
If you are casting to Material class you should probably use SelectedItem instead of SelectedValue. (unless you exactly know what you're doing)
I would guess that you have an event-handler that isn't happy. What exactly does the message say?
You might also be having problems if you are adding the same Material instance to the list multiple times; since IndexOf will only find the first occurrence. This line makes me very suspicious:
mater.Add((Material)cmbMaterial.SelectedValue);
since it could potentially (on consecutive clicks / etc) do exactly this.
Note: if you used BindingList<T> instead all you'd have to doo is Add(...) - no resetting required:
field:
BindingList<Material> mater = new BindingList<Material>();
init grid:
dgvMaterial.DataSource = mater;
add item:
mater.Add(newInstance);
If you assign data source to the DGV you should check element count - if zero then assign null. I don't know why this is the way it is, but I'm doing it in all my forms.
//I'm still analysing the rest of the code

Categories

Resources