|
Dear All,
I add a dolder in solution explorer tree. And I add txt files into it.
How can I read it from there?
Thanks.
|
|
|
|
|
Depends on exactly what you did when you added the files: If you highlight the file and go to the Properties pane, you can set the "Build Action" to "Embedded Resource".
Then go to the project in the Solution Exploerer panel, and open the "Properties" branch.
Double click "Resources.resx".
Drag the text file from the solution folder to the resources page, and drop it.
You can now access the file from the Properties in your code:
string myText = Properties.Resources.MyTextFile; Where "MyTextFile.txt" was the original file name.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi,
I am trying to load a treeview with the list of directories present in the folder location asynchronously in a wizard type form.
The same code works as a separate standalone form.
The below is the code for the wizard form:
public partial class DLWizardPage3 : WizardFormLib.WizardPage
{
frmAlertForm alert;
public delegate void Add(TreeView tv, string value);
public DLWizardPage3(WizardFormBase parent)
: base(parent)
{
InitPage();
}
public DLWizardPage3(WizardFormBase parent, WizardPageType pageType)
: base(parent, pageType)
{
InitPage();
}
public void InitPage()
{
InitializeComponent();
base.Size = this.Size;
this.ParentWizardForm.DiscoverPagePanelSize(this.Size);
}
public override bool SaveData()
{
return true;
}
public override bool ValidateData()
{
return true;
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
_logger.DebugFormat(LogMessageFormatString, "DLWizardPage3::backgroundWorker2_DoWork", "Started loading Directories for Metadata collected...");
BackgroundWorker worker = sender as BackgroundWorker;
Message = "Loading Data... Please Wait...";
worker.ReportProgress(0);
for (int i = 0; i < 10; i++)
{
Message = "Loading Data... Please Wait...";
tvDir.Invoke(new Add(AddRootNode), new object[] { tvDir, CommonData.ProjectPath });
worker.ReportProgress(i * 10);
}
}
private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
alert.Message = Message + e.ProgressPercentage.ToString() + "%";
alert.ProgressValue = e.ProgressPercentage;
}
private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bool isProcessCompleted = false;
if (e.Cancelled == true)
{
lblResult.Text = "";
isProcessCompleted = false;
}
else if (e.Error != null)
{
lblResult.Text = "Error: " + e.Error.Message;
isProcessCompleted = false;
_logger.ErrorFormat(LogExceptionNameMessageFormatString, "DLWizardPage3::backgroundWorker2_RunWorkerCompleted", e.Error.Message);
}
else
{
isProcessCompleted = true;
}
alert.Close();
if (isProcessCompleted)
{
_logger.DebugFormat(LogMessageFormatString, "DLWizardPage3::backgroundWorker2_RunWorkerCompleted", "Completed loading folders for Metadata collected...");
DialogResult diagRes = MessageBox.Show("Has the metadata been collected using Omni Tool?", "Data Load", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
if (diagRes == DialogResult.Yes)
{
CommonData.IsReportGeneratedThroughSOMA = true;
}
else
{
CommonData.IsReportGeneratedThroughSOMA = false;
}
}
}
private void DLWizardPage3_Load(object sender, EventArgs e)
{
if (backgroundWorker2.IsBusy != true)
{
alert = new frmAlertForm(false, ProgressBarStyle.Marquee, 30);
alert.Canceled += new EventHandler<EventArgs>(btnCancel_Click);
alert.Show();
backgroundWorker2.RunWorkerAsync();
}
}
private void ListDirectory(TreeView treeView, string path)
{
treeView.Nodes.Clear();
var rootDirectoryInfo = new DirectoryInfo(path);
CommonData.ProjectName = rootDirectoryInfo.Name;
treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
}
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name);
directoryNode.Expand();
foreach (var directory in directoryInfo.GetDirectories())
{
if ((!Regex.IsMatch(directory.Name, @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$")) && (directory.Name.ToString().ToUpper() != "CSS") && (directory.Name.ToString().ToUpper() != "IMG") && (directory.Name.ToString().ToUpper() != "JS") && (directory.Name.ToString().ToUpper() != "DMV") && (directory.Name.ToString().ToUpper() != "MESSAGES"))
{
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
}
}
return directoryNode;
}
public void AddRootNode(TreeView treeView, string path)
{
treeView.Nodes.Clear();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
}
}
Below is the code AlertForm that shows a progress bar.
public partial class frmAlertForm : Form
{
public string Message { set { lblMessage.Text = value; } }
public int ProgressValue { set { progressBar1.Value = value; } }
public frmAlertForm(bool isCancelVisible)
{
InitializeComponent();
btnCancel.Visible = isCancelVisible;
}
public frmAlertForm(bool isCancelVisible, ProgressBarStyle style, int animationSpeed)
{
InitializeComponent();
btnCancel.Visible = isCancelVisible;
progressBar1.Style = style;
progressBar1.MarqueeAnimationSpeed = animationSpeed;
}
public event EventHandler<EventArgs> Canceled;
private void btnCancel_Click(object sender, EventArgs e)
{
EventHandler<EventArgs> ea = Canceled;
if (ea != null)
ea(this, e);
}
private void frmAlertForm_Load(object sender, EventArgs e)
{
}
}
I am using backgroundWorker to make the asynchronous loading of treeview.
When ever, I add the tree node, I am getting exception "
Cannot access a disposed object. Object name: 'TreeView' " What is it that I am doing wrong in the code.
Kindly help.
Regards,
Rani Iyer
|
|
|
|
|
ranimiyer10 wrote: tvDir.Invoke(new Add(AddRootNode), new object[] { tvDir, CommonData.ProjectPath }); You are accessing the TreeView from another thread.
I'd pass the form as an argument (like you did with the BGW), and invoke on that
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Hello,, I wrote a code for finding the non repeated character from a character array.But the indexof function is not working.It is showing as argument null exception.Can anyone suggest an alternate way to do this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp7
{
class Program
{
public static void Main(string[] args)
{
char[] str = new char[5] { 'a', 'b', 'b', 'a', 'c' };
char result = '0';
for (int index = 0; index < str.Length; index++)
{
if (str.LastIndexOf(str[index]) == str.IndexOf(str[index]))
{
result = str[index];
break;
}
}
Console.Write(result);
Console.ReadKey();
}
}
}
|
|
|
|
|
Just count the number of occurances ("group and count"; dictionary; etc.)
Any char with a count of 1 is "unique".
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Where does this exception occur?
|
|
|
|
|
That code won't even compile: an array of characters does not have an IndexOf or LastIndexOf method - strings do, but arrays of characters don't. There are generic Array.IndexOf and Array.LastIndexOf methods, but they need at least two parameters.
And I wouldn't do it that way: it's going to do a heck of a lot of the same thing a lot of times. That's OK(ish) for a small data sample, but once the size rises, it starts to get very inefficient as you are searching the bulk of your input repeatedly each time round the loop.
How would I do it? Simple: Sort the array, and compare adjacent character pairs. If they are different, that's the character you wanted:
a b b a c
a a b b c See what I mean?
And there is an Array.Sort method which is pretty efficient, even with large arrays.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
public class CharData
{
public char Character { get; set; }
public int Count { get; set; }
}
public class CharCounter : List<CharData>
{
public CharCounter(char[] chars)
{
if (chars == null)
{
throw new ArgumentNullException("The character array parameter cannot be null.");
}
if (chars.Length == 0)
{
throw new InvalidOperationException("The character array cannot be empty.");
}
foreach(char ch in chars)
{
this.Add(ch);
}
}
public void Add(char ch)
{
CharData cd = this.FirstOrDefault(x=>x.Character == ch);
if (cd == null)
{
this.Add(new CharData(){Character = ch, Count=1});
}
else
{
cd.Count++;
}
}
}
Usage:
CharCounter counter = new CharCounter(new char[]{'a','b','b','a','c'});
CharData unique = counter.FirstOrDefault(x=>x.Count == 1);
string msg = (unique == null) ? "No unique characters found":string.Format("First unique character is '{0}'", unique.Character);
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
JSOP what benefit do you get from declaring the class like this
public class CharCounter : List<CharData>
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
I do that all the time because then it lets me black-box stuff that I want the list to be able to do on its own (like parse the array of characters), which has the added benefit of simplifying usage. Just habit more than anything else.
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
I have a class called move. I have instantiations of move in a List Collection called playerMoves. I have an instantiation of the class move called tempMove.
MOVE CLASS:
public class move
{
public string displayName = string.Empty;
public string element = string.Empty;
public int damage = 0;
public int enemyDamageSubtraction = 0;
public int minimumLevel = 0;
}
I am running through playerMoves using a foreach statement (it is in another foreach statement, which is part of the code that gets the data for tempMove), and trying to check if my collection contains a move instantiation with the same data in it.
How do I do that? I researched, but I didn't find anything except for some very complex NuGet Packages that make my head spin!
|
|
|
|
|
Start by implementing IEquatable<T> and overriding GetHashCode and Equals :
How to: Define Value Equality for a Type (C# Programming Guide) | Microsoft Docs[^]
public class Move : IEquatable<Move>
{
...
public override int GetHashCode()
{
unchecked
{
int result = 17;
result = result * 23 + StringComparer.Ordinal.GetHashCode(displayName ?? string.Empty);
result = result * 23 + StringComparer.Ordinal.GetHashCode(element ?? string.Empty);
result = result * 23 + damage.GetHashCode();
result = result * 23 + enemyDamageSubtraction.GetHashCode();
result = result * 23 + minimumLevel.GetHashCode();
return result;
}
}
public override bool Equals(object obj)
{
return Equals(obj as Move);
}
public bool Equals(Move other)
{
if (ReferenceEquals(other, null)) return false;
return string.Equals(displayName, other.displayName, StringComparison.Ordinal)
&& string.Equals(element, other.element, StringComparison.Ordinal)
&& damage == other.damage
&& enemyDamageSubtraction == other.enemyDamageSubtraction
&& minimumLevel == other.minimumLevel;
}
public static bool operator ==(Move left, Move right)
{
return Equals(left, right);
}
public static bool operator !=(Move left, Move right)
{
return !Equals(left, right);
}
}
You can then use the Contains method[^] to see if your list contains an instance with the same values as your temp instance:
Move tempMove = new Move
{
displayName = "...",
element = "...",
damage = ...,
enemyDamageSubtraction = ...,
minimumLevel = ...,
};
bool alreadyInList = playerMoves.Contains(tempMove);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
While I am sure Richard Deeming's excellent answer here will meet your needs ... it's a perfect example of the need for, and use of, 'IEquatable ...
I think it's a good idea to consider the strategy of never allowing duplicates to occur.
I suggest you look closely at your code that instantiates the 'Move class: do you really want to allow duplicate 'displayname properties ? How about 'element ?
If you keep 'displayname values unique, you might consider making a 'struct containing the three 'int properties, and using a Dictionary<string, intdata> to get hash-based look-up.
For issues around use of Strings in a struct, see: <[^].
«... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12
|
|
|
|
|
Hello,
Some Turkish characters (ı,ş..) are not showing up at .pdf. what is wrong at below BaseFont:
BaseFont bF = BaseFont.CreateFont("C:\\windows\\fonts\\timesbd.ttf", "iso-8859-9", BaseFont.EMBEDDED);
iTextSharp.text.Font f = new iTextSharp.text.Font(bF, 12f, iTextSharp.text.Font.NORMAL);
modified 13-Feb-19 21:02pm.
|
|
|
|
|
Hi,
I don't know, however this page[^] would make me try BaseFont.CP1254 instead of "iso-8859-9"
|
|
|
|
|
I want to open with a click on a button, some sort of dialog which contains text in a new window.
The problem is that i want to have both forms active, so the user can click on both. Or at least have the dialog form locked but you can still close it, and original form opened.
I have already created a pop up form but when it pops up, you cant use the original form.
Any suggestions?
|
|
|
|
|
Both usable at once:
MyOtherForm mof = new MyOtherForm();
mof.Show(); Close and continue:
MyOtherForm mof = new MyOtherForm();
if (mof.ShowDialog() == DialogResult.OK)
{
...
}
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Awesome, thanks it works. I have used ShowDialog instead of just Show. Thats way first form was locked.
|
|
|
|
|
You're welcome!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
When you set the 'Owner property of a Form to another Form, then you guarantee that when you 'Show the owned Form, it will be visible in front of (higher in the z-order) the owner Form: [^]
Both Forms will be movable, visible, usable.
«... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12
|
|
|
|
|
Hi all,
I'm EXTREMELY new to c# visual studios and honestly don't understand it at all but have to do a piece of coursework.
I have to create a controller for a washing machine and on the user interface I'd like to have a button labelled 'temperature' that when clicked will scroll through multiple options, like on a real washing machine.
So I've inserted a button and I have a checkedlistbox with all of the available temperatures but really don't know where to go from there.
Is there any way I can have the button click once to select 30C, then when clicked again selects 40C and when clicked again selects 60C (then any clicks after that just repeat the cycle)??
I'd really like to learn how to do this please!
|
|
|
|
|
You're going to need to start by telling us what UI framework you're using. Is it Windows Forms? WPF? ASP.NET WebForms? ASP.NET MVC? ASP.NET Core? Something else?
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Although knowing what environment you are working in would certainly help, the principle is the same in all environment, just the details will change.
The way I'd do it* is to create an array of strings:
private string[] Temperatures = { "30C", "40C", "60C", "90C" }; And a current setting variable:
private int currentTemp = 0; Then each time the button was clicked I'd change it:
private void butTemp_Click(object sender, EventArgs e)
{
currentTemp++;
if (currentTemp >= Temperatures.Length)
{
currentTemp = 0;
}
butTemp.Text = Temperatures[currentTemp];
}
* Well, not really, I'd use a "TemperatureSetting" class instead of strings and temps to hold it all together - but that's the more advanced stuff.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
That would result in an awkward UI: whenever I want anything but 30C, I would need to click the 30C button
I'd rather have a label showing the current temperature setting, and the button saying "Change temperature".
How about a bunch of RadioButtons inside a GroupBox? or a user-defined scrollbar? or ...
|
|
|
|
|