c# - cannot delete the last remaining item in listview - c#

I am working on a project (simple phone book) for personal use. I am having trouble deleting the last remaining item in my listview (listView1). Here you can take a look how it looks like:
So, let's say that I have got 5 contacts in the list and when I try to remove all of them, it's not possible. It is possible to remove only 4 of them. When I try to remove all of them and then close/run the application, there will be no removed contacts. When I try to remove 4 of them and I close/run the program, they would be deleted. When I try to remove the last one, it is not possible either. When I close/run app it would always remain there.
Since it doesn't makes sense to upload the whole code here, you can take a closer look at it at this link.
How can I solve this issue?

This should work for removing items from the listview:
Person person = new Person();
try { person = FindPerson(listView1.SelectedItems[0].Text); } catch { return; }
if (listView1.SelectedItems.Count > 0)
{
try
{
if (listView1.SelectedItems.Count == 0) return;
foreach (ListViewItem eachItem in listView1.SelectedItems)
{
people.RemoveAll(x => x.Name == eachItem.Text);
listView1.Items[listView1.Items.Count - 1].Selected = true;
listView1.Items.Remove(eachItem);
}
}
catch { }
ClearAll();
ReadOnlyON();
}
else
{
MessageBox.Show("Nothing is selected!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);

perhaps you can use the clear method to remove the last item.
ListView1.Clear();
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.clear(v=vs.110).aspx

You can loop through the list backwards and remove each item or use as suggested ListView1.Clear();

Just replace this line
listView1.SelectedItems[0].Remove();
in Remove()
with
foreach ( ListViewItem eachItem in listView1.SelectedItems)
{
listView1.Items.Remove(eachItem);
}
SelectedItems[0].Remove(); does not work for last item.

This is the way I delete items:
void Rmv()
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to delete this contact?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
Remove();
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
void Remove()
{
if (listView1.SelectedItems.Count > 0)
{
Person person = new Person();
person = FindPerson(listView1.SelectedItems[0].Text);
people.RemoveAt(listView1.SelectedItems[0].Index);
foreach (ListViewItem eachItem in listView1.SelectedItems)
{
listView1.Items.Remove(eachItem);
}
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
dateTimePicker1.Value = DateTime.Now;
if (listView1.SelectedItems.Count == 0)
{
textBox1.ReadOnly = false;
textBox2.ReadOnly = false;
textBox3.ReadOnly = false;
textBox4.ReadOnly = false;
textBox5.ReadOnly = false;
textBox6.ReadOnly = false;
dateTimePicker1.Enabled = true;
UserCount();
}
}
else
{
MessageBox.Show("Nothing is selected! ", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
void UserCount()
{
try
{
if ((listView1.Items.Count) == 0)
{
toolStripLabel1.Text = Convert.ToString(listView1.Items.Count) + "& contacts";
}
else if ((listView1.Items.Count) == 1)
{
toolStripLabel1.Text = Convert.ToString(listView1.Items.Count) + "& contact";
}
else
{
toolStripLabel1.Text = Convert.ToString(listView1.Items.Count) + "& contacts";
}
}
catch { }
}

Related

Unable to check all check boxes in a GridView

I am using grid view check box to select all the values in the grid view when i click the check box, but the problem i am facing is it is selecting the only the first page value how ever i have coded to bring all the values in but in design it is not working out
this is the image
i want all the check box to checked in design when i press the all check button.
protected void gvBatch_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType != DataControlRowType.Header && e.Row.RowType != DataControlRowType.Footer && e.Row.RowType != DataControlRowType.Pager)
{
DropDownList ddlcountry1 = (DropDownList)e.Row.FindControl("ddlcountry");
populateLocationValues(ddlcountry1);
{
ArrayList checkboxvalues = (ArrayList)Session["BP_PrdId"];
//string Bp_Id = "";
if (checkboxvalues != null && checkboxvalues.Count > 0)
{
string strBp_Id = ((HiddenField)e.Row.FindControl("hf_ProductLblId")).Value.ToString();
if (checkboxvalues.Contains(strBp_Id))
{
CheckBox myCheckBox = (CheckBox)e.Row.FindControl("chkPLPSltItem");
myCheckBox.Checked = true;
}
}
}
DataSet dsaccess = MenuRestriction();
DataRow dr = null;
string sView = "";
string sEdit = "";
string sInsert = "";
string sDeactive = "";
if (dsaccess.Tables.Count > 0)
{
if (dsaccess.Tables[0].Rows.Count > 0)
{
dr = dsaccess.Tables[0].Rows[0];
sView = dr["MnuRgts_View"].ToString();
sEdit = dr["MnuRgts_Edit"].ToString();
sInsert = dr["MnuRgts_Insert"].ToString();
sDeactive = dr["MnuRgts_DeActivate"].ToString();
if (sInsert == "Y" && sDeactive == "Y")
{
BtnDelete.Visible = true;
imgNew.Visible = true;
}
else
{
BtnDelete.Visible = false;
imgNew.Visible = false;
if (sInsert == "Y")
{
imgNew.Visible = true;
}
if (sDeactive == "Y")
{
BtnDelete.Visible = true;
}
}
}
}
}
}
catch (Exception ex)
{
log.Error("gvBatch_RowDataBound", ex);
}
}
protected void gvBatch_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
RememberOldValues();
gvBatch.PageIndex = e.NewPageIndex;
//RetrieveValues();
BindGrid();
LoadLocation();
//RePopulateValues();
}
private void RememberOldValues()
{
ArrayList checkboxvalues = new ArrayList();
string strBp_Id = "";
foreach (GridViewRow row in gvBatch.Rows)
{
//index = (int)gvBatch.DataKeys[row.RowIndex].Value;
strBp_Id = ((HiddenField)row.FindControl("hf_ProductLblId")).Value.ToString();
bool result = ((CheckBox)row.FindControl("chkPLPSltItem")).Checked;
// Check in the Session
if (Session["BP_PrdId"] != null)
checkboxvalues = (ArrayList)Session["BP_PrdId"];
if (result)
{
if (!checkboxvalues.Contains(strBp_Id))
checkboxvalues.Add(strBp_Id);
}
else
{
if (checkboxvalues.Contains(strBp_Id))
checkboxvalues.Remove(strBp_Id);
}
}
if (checkboxvalues != null && checkboxvalues.Count > 0)
Session["BP_PrdId"] = checkboxvalues;
}
protected void gvBatch_PreRender(object sender, EventArgs e)
{
try
{
if (gvBatch.TopPagerRow != null)
{
((Label)gvBatch.TopPagerRow.FindControl("lbCurrentPage")).Text = (gvBatch.PageIndex + 1).ToString();
((Label)gvBatch.TopPagerRow.FindControl("lbTotalPages")).Text = gvBatch.PageCount.ToString();
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnFirst")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnPrev")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnNext")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnLast")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
DropDownList ddlist = (DropDownList)gvBatch.TopPagerRow.FindControl("ddlPageItems");
ddlist.SelectedIndex = ddlist.Items.IndexOf(ddlist.Items.FindByValue(ViewState["DropDownPageItems"].ToString()));
gvBatch.AllowPaging = true;
gvBatch.TopPagerRow.Visible = true;
}
}
catch (Exception ex)
{
}
}
protected void gvBatch_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "EDIT")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
string strAgentName = ((HiddenField)row.FindControl("hf_loginName")).Value.ToString();
if (strAgentName != "")
{
Response.Redirect("CustomerDetails.aspx?Name=" + strAgentName, false);
}
}
}
catch (Exception ex)
{
log.Error("gvAgentRowcommand_AgentSummary", ex);
}
}
You can keep a boolean field in your code and set its value to true whenever the select all is clicked. When loading new pages, you can check that field to automatically display all checked. The same can be done when exporting the grid also.
you can modify and use the following Method
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells["Column_Name"].Value) == false)
{
item.Cells["Column_Name"].Value = true;
}
}
}
the 'Column_name' is the name of the checkbox column. if you haven'nt named it yet you can also use the index number .
in your case its 0
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == false)
{
item.Cells[0].Value = true;
}
}
}
You should update (ArrayList)Session["BP_PrdId"] to include all the "Id"s of datasource of gridview. then bind data again.

Save file dialog doesn't appear sometimes

I am developing an export function with save file dialog for list view, when list view rows go so much, more than 7000 or much, the save file dialog not appearing don't know why !
Update: added the snippet code, how I am filling the listview !
Here is the code I am using for exporting listview,
private void ExportBTN_Click(object sender, EventArgs e)
{
DialogResult dialogeResult = sfd.ShowDialog();
if (dialogeResult == DialogResult.OK)
{
using ( var tw = new StreamWriter(sfd.FileName))
{
foreach (ListViewItem item in URLListView.Items)
{
tw.WriteLine(item.Text);
}
tw.Close();
XtraMessageBox.Show("All links has been exported successfully.");
AddLog("All links has been exported successfully.");
}
}
}
Here is the way I am filling the listview:
if(URLListView.Items.Count == 0)
{
XtraMessageBox.Show("You have to get the main links first");
return;
}
if (GetInnerLinkBTN.Text == "Stop")
{
enablecontrols(true);
StopGettingInnerLink = true;
GetInnerLinkBTN.Text = "Start Get Innter Links";
}
else if (GetInnerLinkBTN.Text == "Start Get Innter Links")
{
enablecontrols(false);
StopGettingInnerLink = false;
GetInnerLinkBTN.Text = "Stop";
}
foreach (ListViewItem link in URLListView.Items)
{
string href = link.Text.ToString();
if (href.Trim() != string.Empty)
{
//XtraMessageBox.Show(href);
if (StopGettingInnerLink == true)
{
AddLog("Getting links has been stopped successfully!");
StopGettingInnerLink = true;
break;
}
else if(StopGettingInnerLink == false)
{
AddLog("Getting links from " + href);
// MainWebbrowser.Navigate(href);
runbrowserinthread(href);
await Task.Delay(5000);
AddLog("Giving the tool some rest for 5 seconds ! ");
}
}
AddLog("Scrapping inner links has been finished successfully!");
enablecontrols(true);

C# Button with DialogResult Retry

I'm going to use two buttons that have a DialogResult Retry. When you push the button the winform will hide, do something and it pops-up again. I use the While method for this. But if you have two buttons with a retry this won't work unless you set one button DialogResult to Yes and do a While method. But is there a better way to do this, case switch or something?
Note this is within a Class
try
{
// Create a form to select objects.
DialogResult result = System.Windows.Forms.DialogResult.None;
while (result == DialogResult.None || result == DialogResult.Retry)
{
// Picking Objects.
if (result == DialogResult.Retry)
{
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.FileName = "test";
saveFileDialog1.Filter = "Family Files (*.rfa)|*.rfa|All Files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
var dialogResult = saveFileDialog1.ShowDialog();
if (dialogResult == DialogResult.OK)
{
string address = "http://www.autodesk.com/revit-basic-sample-family-2017-enu?_ga=2.28765692.1750602280.1538397390-459409917.1521646598";
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.DownloadFile(address, saveFileDialog1.FileName);
Autodesk.Revit.DB.Family family = null;
using (Transaction tx = new Transaction(doc))
{
tx.Start("Load Family");
if (doc.LoadFamily(saveFileDialog1.FileName, out family))
{
String name = family.Name;
TaskDialog.Show("Revit", "Family file " + name + " has been loaded ");
}
else
{
TaskDialog.Show("Revit", "Can't load the family file or already exists.");
}
tx.Commit();
}
}
if (dialogResult == DialogResult.Cancel)
{
}
}
// Show the dialog.
using (testForm selectionForm = new vuurenForm(commandData))
{
result = selectionForm.ShowDialog();
}
}
return Result.Succeeded;
You may set the DialogResult in the code, not in the form designer. Just double click the buttons and add something like:
private void button1_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Retry;
}
That way both buttons will have the same DialogResult.
Than the loop is OK with only checking for the DialogResult.Retry.
Exactly you can try this code to manage your DialogResult like:
switch(MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo))
{
case DailogResult == DialogResult.Yes:
//Do something
case DailogResult == DialogResult.Retry:
//Do something
}
Actually for two Button objects you have to have two event-handler objects and you can set:
DialogResult = DialogResult.Retry;
In the event that you want to Retry.
You can try this:
var dialogResult = DialogResult.Retry;
while (dialogResult == DialogResult.Retry) {
try {
CheckSomething();
break;
}
catch {
if (dialogResult == DialogResult.Abort) {secondDialog.DialogResult = Retry;}
throw;
}
}
You can also use enums like below:
enum Result {Ignore, Abort,Retry};

Save Records to DataBase using C# sql in windows form datagrid

I'm having trouble when I save my records to DataBase using C# sql windows form Datagrid,I lose all my Records when I restart my application or when I catch an exception error but this problem does not happen often but when there is exception error all my records are lost
Here is my Save button code.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
//Reconnect to Database
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(dataAdapter);
// cb.DataAdapter.Update(ds.Tables["Impi"]);
//Create a new row
DataRow dr = ds.Tables["tblImpi"].NewRow();
//save the record to first column
dr[0] = txtSerial.Text;
//Check data entry if its no empt
if (txtName.Text != "")
{
dr[1] = txtName.Text;
}
//Check if combox has values and assign one the values to it
if (cbModel.Text == "MKI" || cbModel.Text == "MKII")
{
dr[2] = cbModel.Text;
}
if (cbStatus.Text == "Serviceble" || cbStatus.Text == "Unserviceble")
{
dr[3] = cbStatus.Text;
}
if (cbDeprtmnt.Text == "AIR" || cbDeprtmnt.Text == "LAND" || cbDeprtmnt.Text == "NAVY" || cbDeprtmnt.Text == "SPECIAL FORCE")
{
dr[4] = cbDeprtmnt.Text;
}
if (cmbVesrion.Text == "10" || cmbVesrion.Text == "11" || cmbVesrion.Text == "12")
{
dr[5] = cmbVesrion.Text;
}
if (txtGsm.Text.Length != 0)
{
dr[6] = txtGsm.Text;
}
if (txtImei.Text.Length != 0)
{
dr[7] = txtImei.Text;
}
//Check if serial number value is not zero
if ((txtSerial.Text.Length != 0) || (txtGsm.Text.Length!=0) || (txtImei.Text.Length!=0))
{
//Create a search Method to search before you save the serial number
bool search = SearchRecBeforeSave(txtSerial.Text, txtName.Text,txtGsm.Text,txtImei.Text);
//bool search = SearchSerialNumberBeforeSave(txtSerial.Text);
if (search == false)
{
// DialogResult dr2 = MessageBox.Show("Are you sure you want to save this serial number", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (txtGsm.Text == "")
{
txtGsm.Text = "";
txtGsm.ForeColor = Color.Red;
tootip.SetToolTip(txtGsm, txtGsm.Text);
}
if (txtImei.Text == "")
{
txtImei.Text = " ";
txtImei.ForeColor = Color.Red;
tootip.SetToolTip(txtImei, txtImei.Text);
}
if (txtName.Text.Length == 0)
{
txtName.Text = "";
txtName.ForeColor = Color.Red;
tootip.SetToolTip(txtName, txtName.Text);
}
else if (txtGsm.Text != "" && txtImei.Text != "" && txtName.Text.Length != 0)
{
DialogResult dr2 = MessageBox.Show("Are you sure you want to save this serial number", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr2 == DialogResult.Yes)
{
ds.Tables["tblImpi"].Rows.Add(dr);
System.Data.SqlClient.SqlCommandBuilder cb1;
cb1 = new System.Data.SqlClient.SqlCommandBuilder(dataAdapter);
cb1.DataAdapter.Update(ds.Tables["tblImpi"]);
// dataAdapter.Update(ds,"Impi");
// maxRow = maxRow + 1;
// inc = maxRow - 1;
MessageBox.Show("Serial Number Added Successful");
}
}
else
{
//Fix this part
MessageBox.Show("This Serial Number Exist and will create the duplicate.\nSerial Number not Saved");
MessageBox.Show("Data Entry was not saved", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("The information that you have enterd already exist\nPlease Enter a Correct Entries ", "Data Entry");
txtSerial.Text = "Please Enter Impi Serial Number";
txtSerial.ForeColor = Color.Red;
tootip.SetToolTip(txtSerial, txtSerial.Text);
txtName.Text = "Please Enter the Track Number";
txtName.ForeColor = Color.Red;
tootip.SetToolTip(txtName, txtName.Text);
txtGsm.Text = "Please Enter the GSM Sim Number";
txtGsm.ForeColor = Color.Red;
tootip.SetToolTip(txtGsm, txtGsm.Text);
txtImei.Text = "Please Enter the IMEI Number ";
txtImei.ForeColor = Color.Red;
tootip.SetToolTip(txtImei, txtImei.Text);
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
//MessageBox.Show("Incorrect Data Entry", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
con.Close();
}
here is the answer for the question I haves asked I managed to solved it
#region Save the Records to the DataBase
private void btnSave_Click(object sender, EventArgs e)
{
try
{
//Reconnect to Database
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(dataAdapter);
//Create a new row
DataRow dr = ds.Tables["tblImpi"].NewRow();
//save the record to first column
dr[0] = txtSerial.Text;
//Check data entry if its not empty
if (txtcallSign.Text != "")
{
dr[1] = txtcallSign.Text;
}
//Check if ip textbox is empty
if (txtIp.Text != "")
{
dr[2] = txtIp.Text;
}
//Check if port is empty
if (txtPort.Text != "")
{
dr[3] = txtPort.Text;
}
//check if gsm txtbox is empty
if (txtGsm.Text != "")
{
dr[4] = txtGsm.Text;
}
//check iriduim txtbox
if (txtiriduim.Text != "")
{
dr[5] = txtiriduim.Text;
}
//check software version
if (txtSoftVersion.Text != "")
{
dr[6] = txtSoftVersion.Text;
}
//Check if serial number,gsm sim,iriduim value is not zero
if ((txtSerial.Text.Length != 0) || (txtGsm.Text.Length != 0) || (txtiriduim.Text.Length != 0))
{
//Create a search Method to search before you save the serial number
bool search = SearchRecBeforeSave(txtSerial.Text, txtGsm.Text, txtiriduim.Text);
//bool search = SearchSerialNumberBeforeSave(txtSerial.Text);
if (search == false)
{
DialogResult dr2 = MessageBox.Show("Do you want to save", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr2 == DialogResult.Yes)
{
ds.Tables["tblImpi"].Rows.Add(dr);
System.Data.SqlClient.SqlCommandBuilder cb1;
cb1 = new System.Data.SqlClient.SqlCommandBuilder(dataAdapter);
cb1.DataAdapter.Update(ds.Tables["tblImpi"]);
MessageBox.Show("Data Saved","Save");
}
// DialogResult dr2 = MessageBox.Show("Are you sure you want to save this serial number", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
else if (txtGsm.Text == "")
{
txtGsm.Text = "";
txtGsm.ForeColor = Color.Red;
tootip.SetToolTip(txtGsm, txtGsm.Text);
}
else if (txtiriduim.Text == "")
{
txtiriduim.Text = " ";
txtiriduim.ForeColor = Color.Red;
tootip.SetToolTip(txtiriduim, txtiriduim.Text);
}
else if (txtcallSign.Text.Length == 0)
{
txtcallSign.Text = "";
txtcallSign.ForeColor = Color.Red;
tootip.SetToolTip(txtcallSign, txtcallSign.Text);
}
}
else
{
MessageBox.Show("The information that you have enterd already exist\nPlease Enter a Correct Entries ", "Data Entry");
txtSerial.Text = "Please Enter Impi Serial Number";
txtSerial.ForeColor = Color.Red;
tootip.SetToolTip(txtSerial, txtSerial.Text);
txtcallSign.Text = "Please Enter Call Sign";
txtcallSign.ForeColor = Color.Red;
tootip.SetToolTip(txtcallSign, txtcallSign.Text);
txtIp.Text = "Please Enter Ip Adress";
txtIp.ForeColor = Color.Red;
tootip.SetToolTip(txtIp, txtIp.Text);
txtPort.Text = "Please Enter Port Number";
txtPort.ForeColor = Color.Red;
tootip.SetToolTip(txtPort, txtPort.Text);
txtGsm.Text = "Please Enter the GSM Sim Number";
txtGsm.ForeColor = Color.Red;
tootip.SetToolTip(txtGsm, txtGsm.Text);
txtiriduim.Text = "Please Enter the IMEI Number ";
txtiriduim.ForeColor = Color.Red;
tootip.SetToolTip(txtiriduim, txtiriduim.Text);
}
}
else if ((txtSerial.Text == "") && (txtIp.Text == "") && (txtPort.Text == "") && (txtiriduim.Text == "") && txtGsm.Text == "")
{
MessageBox.Show("Please Enter a data", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
//MessageBox.Show("Incorrect Data Entry", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
con.Close();
}

how to check if the item [name & subItem's text] is already exists in another listView?

i making a file transfer (server-client) application .. i have two listviewS to explore Local PC and Remote PC .. before send/receive the items.. i need to check if there's another file or folder has the same name at the destination path..
when i press on the button [send or receive] the item added to a list.. then when i press on button [Start Transfer] .. it starts.
so the AddItems Method called when i press the button Receive or Send .. i get the SelectedItems from the source ListView .. and the Items of the destination ListView ... then i check for each item in SelectedItems if it is exists in Items
i tried to use
items.Contain(item)
but it didn't work it always gave me false even if the item is already exists.
so i used items.ContainKey and it worked .. but in case that i have a file named "Temp" with no extension and a folder in destination path also named "Temp" .. it will returns True .. and that's my problem ..
bool YesToAll = false;
public void AddItems(ListView.SelectedListViewItemCollection selectedItems, ListView.ListViewItemCollection items,TransferType type,string destPath)
{
foreach(ListViewItem item in selectedItems)
{
if (items.ContainsKey(item.Name) && !YesToAll)
{
MyMessageBox msgbox = new MyMessageBox("Item is already exists .. Do you want to replace (" + item.Text + ") ?");
msgbox.ShowDialog();
if (msgbox.DialogResult == DialogResult.Yes)
{
Add(item, type, destPath);
}
else if (msgbox.DialogResult == DialogResult.OK)
{
YesToAll = true;
Add(item, type, destPath);
}
else if (msgbox.DialogResult == DialogResult.No)
{
continue;
}
else
{
return;
}
}
else
{
Add(item, type, destPath);
}
}
YesToAll = false;
}
private void Add(ListViewItem item,TransferType type,string path)
{
ListViewItem newItem = (ListViewItem)item.Clone();
newItem.ImageIndex = imageList1.Images.Add(item.ImageList.Images[item.ImageIndex],Color.Transparent);
newItem.SubItems.Add(type.ToString());
newItem.SubItems.Add(path);
newItem.Tag = type;
listView1.Items.Add(newItem);
}
YesToAll is set to true when the user clicked on [Yes to all] button in the confirm dialogbox.
TransferType is just to mark the item if it's going to use SendMethod or ReceiveMethod
public enum TransferType
{
Send , Receive
};
so how do i fix that .. should i use a custom method instead of [Contains] that checks for the name and for the type (file or folder) because each item is already has a subItem which tell if it is a folder or a file
thanks in advance.
One quick Idea.
You could utilize your Tag-Property to contain more than just the Transfer-Type.
Since it can contain Objects, you could Create a custom class containing your transfer-type and also more information about the entry. IsDirectory for example and you could utilize that at a later point.
Hope that helps
Sascha
Please try this
bool YesToAll = false;
public void AddItems(ListView.SelectedListViewItemCollection selectedItems, ListView.ListViewItemCollection items,TransferType type,string destPath)
{
foreach(ListViewItem item in selectedItems)
{
if (items.ContainsKey(item.Name) && !YesToAll)
{
ListViewItem lvtemp=items.Find(item.Name)[0];
if((lvTemp.SubItems[0].Text!= "[Folder]" && item.SubItem[0].Text!="[Folder]" ) or (lvTemp.SubItems[0].Text== item.SubItems[0].Text && lvTemp.SubItems[0].Text="[Folder]") )
{
MyMessageBox msgbox = new MyMessageBox("Item is already exists .. Do you want to replace (" + item.Text + ") ?");
msgbox.ShowDialog();
if (msgbox.DialogResult == DialogResult.Yes)
{
Add(item, type, destPath);
}
else if (msgbox.DialogResult == DialogResult.OK)
{
YesToAll = true;
Add(item, type, destPath);
}
else if (msgbox.DialogResult == DialogResult.No)
{
continue;
}
else
{
return;
}
}
}
else
{
Add(item, type, destPath);
}
}
YesToAll = false;
}
private void Add(ListViewItem item,TransferType type,string path)
{
ListViewItem newItem = (ListViewItem)item.Clone();
newItem.ImageIndex = imageList1.Images.Add(item.ImageList.Images[item.ImageIndex],Color.Transparent);
newItem.SubItems.Add(type.ToString());
newItem.SubItems.Add(path);
newItem.Tag = type;
listView1.Items.Add(newItem);
}

Categories