Getting warning CS0469 how to solve? [duplicate] - c#

I've been searching for answers everywhere and I can't seem to solve mine. Anyone know a solution for this? I'm getting the following errors:
Line 25: Field 'Champion_Item_List_Downloader.MainForm.championsList' is never assigned to, and will always have its default value null (CS0649)
Line 26: Field 'Champion_Item_List_Downloader.MainForm.rolesList' is never assigned to, and will always have its default value null (CS0649)
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.ComponentModel;
namespace Champion_Item_List_Downloader
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
const string listFile = "Lists.txt";
private System.Collections.Generic.List<string> championsList;
private System.Collections.Generic.List<string> rolesList;
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
loadList(listFile);
}
public void loadList(string file){
try {
using (StreamReader r = new StreamReader(file))
{
string line;
bool isChamp = false;
while ((line = r.ReadLine()) != null)
{
if (line == #"[Champions]") {
isChamp = true;
}
if(line != #"[Champions]" && line != #"[Types]" && line != "")
{
if(isChamp == true){
championsList.Add(line);
} else {
rolesList.Add(line);
}
}
}
}
} catch (Exception) {
}
}
public void loadStringList(string file, List<string> list){
try {
using (StreamReader r = new StreamReader(file))
{
string line;
while ((line = r.ReadLine()) != null)
{
list.Add(line);
}
}
} catch (Exception) {
}
}
void Btn_DownloadClick(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
progressBar.Maximum = championsList.Count * rolesList.Count;
int count = 0;
progressBar.Value = 0;
string fileName = "";
string url = "";
string path = "";
foreach (string c in championsList)
{
foreach (string r in rolesList)
{
try {
fileName = c + #"_" + r + #"_scrape.json";
url = #"http://www.lolflavor.com/champions/" + c + #"/Recommended/" + fileName;
path = #"Champions\" + c + #"\Recommended\";
Directory.CreateDirectory(path);
webClient.DownloadFile(new Uri(url), path + fileName);
count++;
progressBar.Value = count;
} catch (Exception) {
}
}
}
progressBar.Value = progressBar.Maximum;
MessageBox.Show("Download completed!\n" + count.ToString() + " item lists successfully downloaded.");
}
void MainFormLoad(object sender, System.EventArgs e)
{
throw new NotImplementedException();
}
}
}

You have not initialized your lists anywhere.
Try initializing them where they are declared:
private System.Collections.Generic.List<string> championsList = new System.Collections.Generic.List<string>();
private System.Collections.Generic.List<string> rolesList = new System.Collections.Generic.List<string>();
Or within the constructor:
private System.Collections.Generic.List<string> championsList;
private System.Collections.Generic.List<string> rolesList;
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
// loadList uses these lists so they should be initialized before the call to loadList to avoid a NullReferenceException.
championsList = new System.Collections.Generic.List<string>();
rolesList = new System.Collections.Generic.List<string>();
loadList(listFile);
}
Or lazily at the time they are needed:
private System.Collections.Generic.List<string> championsList;
private System.Collections.Generic.List<string> rolesList;
public void loadList(string file){
if (championsList == null) championsList = new System.Collections.Generic.List<string>();
if (rolesList == null) rolesList = new System.Collections.Generic.List<string>();
try {
using (StreamReader r = new StreamReader(file))
{
...
}
} catch (Exception) {
}
}
void Btn_DownloadClick(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
if (championsList == null) championsList = new System.Collections.Generic.List<string>();
if (rolesList == null) rolesList = new System.Collections.Generic.List<string>();
progressBar.Maximum = championsList.Count * rolesList.Count;
int count = 0;
progressBar.Value = 0;
string fileName = "";
string url = "";
string path = "";
foreach (string c in championsList)
{
foreach (string r in rolesList)
{
...
}
}
progressBar.Value = progressBar.Maximum;
MessageBox.Show("Download completed!\n" + count.ToString() + " item lists successfully downloaded.");
}
P.S. because you already have using System.Collections.Generic declared, you could write it more simply as:
private List<string> championsList = new List<string>();
private List<string> rolesList = new List<string>();

There is never a call to championsList = new System.Collections.Generic.List<string>().
Thus it's never initialized

Related

Regarding strongly typed dataset in windows form application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GST.Masters
{
public partial class Customers : Heptanesia.Winforms.Ui.Forms.MainUC
{
public static string recCode
{ get; set; }
public string RC;
public bool insertFlag;
public Data.GSTDb.CustomersRow r;
public Data.GSTDb.CustomersGSTNosRow gr;
public Data.GSTDb.CustomersDataTable dt = new Data.GSTDb.CustomersDataTable();
public Customers()
{
InitializeComponent();
recCode = Guid.NewGuid().ToString();
this.Load += new EventHandler(this.Customers_Load);
this.Ts.SaveClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SaveClickedEventHandler(this.Ts_SaveClicked);
this.Ts.AddNewClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.AddNewClickedEventHandler(this.Ts_AddNewClicked);
this.Ts.SearchClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SearchClickedEventHandler(this.Ts_SearchClicked);
this.DgGST.CellValidated += (sender, e) =>
{
string name = this.DgGST.Columns[e.ColumnIndex].Name;
if (name == "DGCCountryCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.statesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCStateCode"].Value = null;
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
else if (name == "DGCStateCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.citiesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
};
}
private void Ts_AddNewClicked(object sender, EventArgs e)
{
this.gSTDb.Customers.Rows.Clear();
r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter CGT = new Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter();
CGT.FillByParentCode(gSTDb.CustomersGSTNos, r.RecCode);
}
private void Ts_SearchClicked(object sender, EventArgs e)
{
Heptanesia.Winforms.Ui.Forms.SearchForm sf = new Heptanesia.Winforms.Ui.Forms.SearchForm();
sf.DataSource = new Data.GSTDbTableAdapters.CustomersTableAdapter().GetData();
sf.DisplayColumns = new string[] { "Name" };
sf.DisplayHeaders = new string[] { "Customers Name" };
sf.DisplayWidths = new int[] { 200 };
if (sf.ShowDialog(this) == DialogResult.OK)
{
this.RC = sf.ReturnRow["RecCode"].ToString();
this.customersTableAdapter.FillByRecCode(this.gSTDb.Customers, RC);
}
}
private void Ts_SaveClicked(object sender, EventArgs e)
{
string message = "Error: ";
try
{
this.customersBindingSource.EndEdit();
//if (this.DgGST.CurrentRow.DataBoundItem != null)
this.fkCustomerGSTNosCustomersBindingSource.EndEdit();
if (this.gSTDb.Customers.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.customersBindingSource, this.gSTDb.Customers.GetErrors()[0]);
else if (this.gSTDb.CustomersGSTNos.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.fkCustomerGSTNosCustomersBindingSource, this.gSTDb.CustomersGSTNos.GetErrors()[0]);
else
{
this.gSTDb.Customers.BeforeSave();
this.gSTDb.CustomersGSTNos.BeforeSave();
Data.GSTDbTableAdapters.TableAdapterManager tm = new Data.GSTDbTableAdapters.TableAdapterManager();
tm.CustomersTableAdapter = this.customersTableAdapter;
tm.CustomersGSTNosTableAdapter = this.customersGSTNosTableAdapter;
tm.UpdateAll(this.gSTDb);
message = "Record(s) Saved Successfully";
}
}
catch (Exception ex)
{
message += ex.Message;
}
MessageBox.Show(message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Customers_Load(object sender, EventArgs e)
{
this.FormIsLoading = true;
this.customersTableAdapter.Fill(this.gSTDb.Customers);
this.customersGSTNosTableAdapter.Fill(this.gSTDb.CustomersGSTNos);
this.countriesTableAdapter.Fill(this.gSTDb.Countries);
this.statesTableAdapter.Fill(this.gSTDb.States);
this.citiesTableAdapter.Fill(this.gSTDb.Cities);
this.gSTDb.Customers.Rows.Clear();
if (this.gSTDb.Customers.Rows.Count == 0)
{
Data.GSTDb.CustomersRow r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
}
this.FormIsLoading = false;
}
private void DgGST_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception is ArgumentException)
{
object value = DgGST.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (!((DataGridViewComboBoxColumn)DgGST.Columns[e.ColumnIndex]).Items.Contains(value))
{
((DataGridViewComboBoxCell)DgGST[e.ColumnIndex, e.RowIndex]).Value = DBNull.Value;
//((DataGridViewComboBoxColumn)dgv.Columns[e.ColumnIndex]).Items.Add(value);
e.ThrowException = false;
}
}
else
{
MessageBox.Show(e.Exception.Message);
e.Cancel = true;
}
}
}
}
I am developing one simple invoice application in which I am having a simple Customer screen module.A Customer can have any number of GST records in the Datagridview.The Screen is based on Customer Masters(Textboxes) and Customers Master Details(Datagridview) relationship through foreign keys. And I am Using Strongly Typed Dataset in this project as a xsd file.This Screen has 3 buttons i.e.New,Save and Find toolstrip menu.
When I start adding records after clicking on New Buttonstrip and and save ,it saves it successfully and when I press New Ideally it should clear the rows.The main issue here is that it is not clearing the rows??
I am enclosing the cs file here.
What I have tried:
Everything as I can Do.
Clearing the Rows through Rows.Clear(); 2) I tried clearing
Binding Source and DataGridview after setting it null.
Nothing Worked.

Cannot Implicitly convert type "String" to "Windows.Security.Credentials.PasswordCredential"

Cannot Implicitly convert type "String" to "Windows.Security.Credentials.PasswordCredential"
After about 4 hours of searching I cannot figure out this error. I am using the Windows 10 IOT Core on a RPI 3. My program is pretty basic, however I can not convert the datatype within the code to resolve the error.
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using Windows.Devices.WiFi;
using Windows.Networking.Connectivity;
using Windows.Security.Credentials;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WiFiConnect
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class WiFiConnect_Scenario : Page
{
MainPage rootPage;
private WiFiAdapter firstAdapter;
public ObservableCollection<WiFiNetworkDisplay> ResultCollection
{
get;
private set;
}
public WiFiConnect_Scenario()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
ResultCollection = new ObservableCollection<WiFiNetworkDisplay>();
rootPage = MainPage.Current;
// RequestAccessAsync must have been called at least once by the app before using the API
// Calling it multiple times is fine but not necessary
// RequestAccessAsync must be called from the UI thread
var access = await WiFiAdapter.RequestAccessAsync();
if (access != WiFiAccessStatus.Allowed)
{
rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
}
else
{
DataContext = this;
var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDevice Selector());
if (result.Count >= 1)
{
firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
var button = new Button();
button.Content = string.Format("Scan Available Wifi Networks");
button.Click += Button_Click;
Buttons.Children.Add(button);
}
else
{
rootPage.NotifyUser("No WiFi Adapters detected on this machine.", NotifyType.ErrorMessage);
}
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
await firstAdapter.ScanAsync();
ConnectionBar.Visibility = Visibility.Collapsed;
DisplayNetworkReport(firstAdapter.NetworkReport);
}
private void DisplayNetworkReport(WiFiNetworkReport report)
{
rootPage.NotifyUser(string.Format("Network Report Timestamp: {0}", report.Timestamp), NotifyType.StatusMessage);
ResultCollection.Clear();
foreach (var network in report.AvailableNetworks)
{
ResultCollection.Add(new WiFiNetworkDisplay(network, firstAdapter));
}
}
private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null)
{
return;
}
// Show the connection bar
ConnectionBar.Visibility = Visibility.Visible;
// Only show the password box if needed
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
NetworkKeyInfo.Visibility = Visibility.Collapsed;
}
else
{
NetworkKeyInfo.Visibility = Visibility.Visible;
}
}
private async void ConnectButton_Click(object sender, RoutedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null || firstAdapter == null)
{
rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage);
return;
}
WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;
if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true)
{
reconnectionKind = WiFiReconnectionKind.Automatic;
}
WiFiConnectionResult result;
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
}
else
{
FileStream file = new FileStream("final-wordlist.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
sr.ReadLine();
var textLines = File.ReadAllLines("final-wordlist.txt");
foreach (var line in textLines)
{
string[] dataArray = line.Split(' ');
foreach (var item in dataArray)
{
PasswordCredential credential = line;
//string credential = line.ToString();
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
}
}
// Only the password potion of the credential need to be supplied
}
if (result.ConnectionStatus == WiFiConnectionStatus.Success)
{
rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);
// refresh the webpage
webViewGrid.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
refreshBrowserButton.Visibility = Visibility.Visible;
}
else
{
rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
}
// Since a connection attempt was made, update the connectivity level displayed for each
foreach (var network in ResultCollection)
{
network.UpdateConnectivityLevel();
}
}
private void Browser_Toggle_Click(object sender, RoutedEventArgs e)
{
if (webViewGrid.Visibility == Visibility.Visible)
{
webViewGrid.Visibility = Visibility.Collapsed;
refreshBrowserButton.Visibility = Visibility.Collapsed;
toggleBrowserButton.Content = "Show Browser Control";
}
else
{
webViewGrid.Visibility = Visibility.Visible;
refreshBrowserButton.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
}
}
private void Browser_Refresh(object sender, RoutedEventArgs e)
{
webView.Refresh();
}
}
}
This worked for me. The problem was it was it need more than one var to fill it.
var credential = new PasswordCredential("Module", "Username", "Password");
Try this:
PasswordCredential credential = null;
if (!string.IsNullOrEmpty(line))
{
credential = new PasswordCredential()
{
Password = line
};
}

Why doesn't my class write to a text file?

Here is my AddReservation Form code. Notice that I call the Piper.WritePiper() method and pass in the Name and Seat that the user enters. I'm not sure why this isn't working. I'm not getting any errors or anything. I am simply just wanting a user to be able to enter their name and seat that they would like to take on the plane and then update the file. Please tell me what I am doing wrong... Thank you in advance!!
public partial class frmAddReservation : Form
{
public frmAddReservation()
{
InitializeComponent();
}
List<Seating> piperSeating = new List<Seating>();
List<Seating> cessnaSeating = new List<Seating>();
private void frmAddReservation_Load(object sender, EventArgs e)
{
piperSeating = Piper.GetPiperReservations();
cessnaSeating = Cessna.GetCessnaReservations();
}
private void btnShowPiper_Click(object sender, EventArgs e)
{
listFlight.Items.Add("Piper Seating Chart:");
listFlight.Items.Add("");
//loop through all the seats
foreach (Seating plane in piperSeating)
{
// add the name of plane to the listbox
listFlight.Items.Add(plane.Name + " " + plane.Seat);
}
}
private void btnAddPiper_Click(object sender, EventArgs e)
{
string Name;
int Seat;
if (DataValid())
{
Name = txtName.Text;
Seat = Convert.ToInt16(txtSeat.Text);
Piper.WritePiper(Name, Seat);
}
}
private bool DataValid()
{
bool isOK = false;
if (CheckSeat(txtSeat))
{
isOK = true;
}
return isOK;
}
private bool CheckSeat(TextBox tbox)
{
bool isOK = true;
try
{
Convert.ToDouble(tbox.Text);
}
catch
{
isOK = false;
}
return isOK;
}
}
Here is my Piper.cs class:
public static class Piper
{
private const string dir = #"Z:\Desktop\Windows 7 Files\C#.net\Reservations\Reservations\Reservations\";
private const string path = dir + "PiperDat.txt";
public static List<Seating> GetPiperReservations()
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
StreamReader textIn =
new StreamReader(
new FileStream(path, FileMode.Open, FileAccess.Read));
List<Seating> personList = new List<Seating>();
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
string[] columns = row.Split(',');
Seating person = new Seating();
person.Name = columns[0];
person.Seat = Convert.ToInt16(columns[1]);
personList.Add(person);
}
textIn.Close();
return personList;
}
public static void WritePiper(string Name, int Seat)
{
List<Seating> piperSeating = new List<Seating>();
piperSeating = Piper.GetPiperReservations();
StreamWriter textOut =
new StreamWriter(
new FileStream(path, FileMode.Open, FileAccess.Write));
foreach (Seating plane in piperSeating)
{
Name = plane.Name;
Seat = plane.Seat;
textOut.Write(Name + ",");
textOut.WriteLine(Seat);
}
}
}
Look at the WritePiper method.
It just reads the file and then writes it back, without any changes. The values in the parameters are ignored, the parameters are just used as temporary storage for the data when it is written to the file.
You need to include the values in the parameters as an item, either by adding it to the list, or by writing it to the file along with the items in the list.
Example:
Seating person = new Seating();
person.Name = Name;
person.Seat = Seat;
piperSeating.Add(person);
I think the cause of your issue might be having forgotten the closure of the file, in alternative you might force the text to flush with textOut.Flush().
Try adding textOut.Close() at the end of the WritePiper(...) method.

what might be causing this to fill this treeview multiple times?

I found this code online. It works, but for some reason it loads the file directory twice.
namespace DockSample.Controls
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using Microsoft.VisualBasic.FileIO;
using DockSample;
//TODO: Add options for filtering by robot
public class SolutionExplorer : TreeView
{
public SolutionExplorer()
{
this.BeforeExpand += customBeforeExpand;
this.Nodes.Clear();
CreateTree(this);
}
private bool CreateTree(TreeView treeView)
{
bool returnValue = false;
try
{
// Create Desktop
TreeNode desktop = new TreeNode();
// desktop.Text = "Desktop";
// desktop.Tag = "Desktop";
// desktop.Nodes.Add("");
// treeView.Nodes.Add(desktop);
// Get driveInfo
foreach (DriveInfo drv in DriveInfo.GetDrives())
{
TreeNode fChild = new TreeNode();
if (drv.DriveType == DriveType.CDRom)
{
fChild.ImageIndex = 1;
fChild.SelectedImageIndex = 1;
}
else if (drv.DriveType == DriveType.Fixed)
{
fChild.ImageIndex = 0;
fChild.SelectedImageIndex = 0;
}
fChild.Text = drv.Name;
fChild.Nodes.Add("");
treeView.Nodes.Add(fChild);
returnValue = true;
}
}
catch
{
returnValue = false;
}
return returnValue;
}
/* Method :EnumerateDirectory
* Author : Chandana Subasinghe
* Date : 10/03/2006
* Discription : This is use to Enumerate directories and files
*
*/
public TreeNode EnumerateDirectory(TreeNode parentNode, List<string> thisFilter)
{
try
{
DirectoryInfo rootDir;
// To fill Desktop
Char[] arr = { '\\' };
string[] nameList = parentNode.FullPath.Split(arr);
string path = "";
if (nameList.GetValue(0).ToString() == "Desktop")
{
path = SpecialDirectories.Desktop + "\\";
for (int i = 1; i < nameList.Length; i++)
{
path = path + nameList[i] + "\\";
}
rootDir = new DirectoryInfo(path);
}
// for other Directories
else
{
rootDir = new DirectoryInfo(parentNode.FullPath + "\\");
}
parentNode.Nodes[0].Remove();
foreach (DirectoryInfo dir in rootDir.GetDirectories())
{
TreeNode node = new TreeNode();
node.Text = dir.Name;
node.Nodes.Add("");
parentNode.Nodes.Add(node);
}
//Fill files
foreach (FileInfo file in rootDir.GetFiles())
{
if (isValidFilter(getExtention(file.Name)))
{
TreeNode node = new TreeNode();
node.Text = file.Name;
node.ImageIndex = 2;
node.SelectedImageIndex = 2;
parentNode.Nodes.Add(node);
}
}
}
catch
{
}
return parentNode;
}
private bool isValidFilter(string ext)
{
bool result = false;
foreach(string s in filter)
{
if (ext == s)
result = true;
}
return result;
}
private string getExtention(string filename)
{
return filename.Substring(filename.IndexOf("."));
}
private void customBeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (e.Node.Nodes[0].Text == "")
{
TreeNode node = this.EnumerateDirectory(e.Node,filter);
}
}
private List<string> filter = new List<string>();
public List<string> Filter
{
get { return filter; }
set { filter = value; }
}
private void InitializeComponent()
{
this.SuspendLayout();
this.ResumeLayout(false);
}
}
}
The constructor of your control runs at both design time and run time. So as soon as you drop the control on the form, it will fill the tree view. Problem is, the nodes will be serialized to InitializeComponent(). Take a look at the Designer.cs file for your form, you'll find them back there. When you run the form, the constructor runs again, doubling the list.
You need to prevent the constructor from adding the nodes at design time. That's a bit difficult to do, you'd normally use the DesignMode property but it isn't set to true yet in the constructor. Do it like this instead:
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
if (!DesignMode && treeView.Nodes.Count == 0) {
CreateTree(this);
}
}
Or do it explicitly by adding a public method that you call in the form's constructor or OnLoad method. Which is rather wise, you might want to catch exceptions. Always likely when you tinker with the file system.

Trouble getting my button to call my class

I have a Windows Form application. What this application does, is let the user browse to a drive/folder they wish to have files renamed for. This app renames files that have "invalid" characters (that are defined in a RegEx pattern).
What i want to happen here is, after the user decides which drive/folder to use, a datagridview pops up showing the user files in the drive/folder that are going to be renamed. The user then clicks a button to actually rename the files. I'm having trouble though getting the code for my button in DriveRecursion_Results.cs set up. Can anybody help me? Code plz -- i'm extremely new to this and need syntax to look at to understand.
Form1 code:
namespace FileMigration2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderSelect("Please select:");
}
public string FolderSelect(string txtPrompt)
{
//Value to be returned
string result = string.Empty;
//Now, we want to use the path information to population our folder selection initial location
string initialPathDir = (#"C:\");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
{
retPath = "";
}
DriveRecursion_Results dw = new DriveRecursion_Results();
dw.Show();
dw.DriveRecursion(retPath);
result = retPath;
}
return result;
}
}
}
DriveRecursion_Results.cs code: [the button is in here that i need help with!]
namespace FileMigration2
{
public partial class DriveRecursion_Results : Form
{
public DriveRecursion_Results()
{
InitializeComponent();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DriveRecursion(string retPath)
{
//recurse through files. Let user press 'ok' to move onto next step
// string[] files = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
//string replacement = "";
Regex regEx = new Regex(pattern);
string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
List<string> filePath = new List<string>();
dataGridView1.Rows.Clear();
try
{
foreach (string fileNames in fileDrive)
{
if (regEx.IsMatch(fileNames))
{
string fileNameOnly = Path.GetFileName(fileNames);
string pathOnly = Path.GetDirectoryName(fileNames);
DataGridViewRow dgr = new DataGridViewRow();
filePath.Add(fileNames);
dgr.CreateCells(dataGridView1);
dgr.Cells[0].Value = pathOnly;
dgr.Cells[1].Value = fileNameOnly;
dataGridView1.Rows.Add(dgr);
filePath.Add(fileNames);
}
else
{
DataGridViewRow dgr2 = new DataGridViewRow();
dgr2.Cells[0].Value = "No Files To Clean Up";
dgr2.Cells[1].Value = "";
}
}
}
catch (Exception e)
{
StreamWriter sw = new StreamWriter(retPath + "ErrorLog.txt");
sw.Write(e);
}
}
private void button1_Click(object sender, EventArgs e)
{
//What do i type in here to call my FileCleanUp method???
}
}
SanitizeFileNames.cs code:
namespace FileMigration2
{
public class SanitizeFileNames
{
public static void FileCleanup(List<string>filePath)
{
string regPattern = "*[\\~#%&*{}/<>?|\"-]+*";
string replacement = "";
Regex regExPattern = new Regex(regPattern);
foreach (string files2 in filePath)
{
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
catch (Exception ex)
{
//write to streamwriter
}
}
}
}
}
}
Any help is appreciated!
Thanks :)
Put
public partial class DriveRecursion_Results : Form {
List<string> filePath;
and in driveRecursion method, just use
filePath = new List<string>();
and in the action button method, why don't you do
if(filePath != null)
SanitizeFileNames.FileCleanup(filePath);
You call filePath.Add twice ?
Your 'else' is in the wrong place too.
What is dgr2?

Categories