Showing the values when form loaded - c#

Hi all i have main form with a treeview control with a set of files displayed under each node. If i had my mouse over that node i will read the values that are present in the text file by using the following code
private void treeViewACH_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e)
{
string strFile = string.Empty;
System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
messageBoxCS.AppendFormat(" {0}", e.Node);
strFile = messageBoxCS.ToString().Substring(11);
strFilePath = Directory.GetCurrentDirectory();
strFilePath = Directory.GetParent(strFilePath).ToString();
strFilePath = Directory.GetParent(strFilePath).ToString();
strFilePath = strFilePath + "\\ACH" + "\\" + strFile;
if ((File.Exists(strFilePath)))
{
StreamReader sr = new StreamReader(strFilePath);
StringComparison compareType = StringComparison.InvariantCultureIgnoreCase;
string fileName = Path.GetFileNameWithoutExtension(strFilePath);
string extension = Path.GetExtension(strFilePath);
if (fileName.StartsWith("FileHeader", compareType)
&& extension.Equals(".txt", compareType))
{
string s = sr.ReadToEnd();
StringBuilder sb = new StringBuilder();
//sb.Append("RecordTypeCode\tPriorityCode");
//sb.Append("\n");
//sb.Append("--------------------------------------------------");
//sb.Append("\n");
objFile.ReferenceTypeCode = s.Substring(0, 1);
sb.Append(objFile.ReferenceTypeCode);
string PriorCode = s.Substring(1, 2);
sb.Append(PriorCode);
objFile.getValues(sb.ToString());
frmTemp frmtemp = new frmTemp();
frmtemp.Show();
}
}
Now i would like to place the values in each textboxes on the form load. But as it is a different form i can not access the values from the business layer
I have coded like this on form load
BL.FileHeader objFile = new FileHeader();
private void frmTemp_Load(object sender, EventArgs e)
{
textBox1.Text = objFile.ReferenceTypeCode;
}
But i am unable to display the values any help please..

Add a property to your frmTemp class for each value that you want to display. In your NodeMouseHover handler, assign values to those properties right after you create the instance of the form. Then, in the frmTemp_Load handler, assign the values of those properties to the TextBox controls.

Got the answer by the following
frmTemp frmtmp = new frmTemp(strFileHeader);
frmtmp.Show();
public frmTemp(string str)
{
InitializeComponent();
if (str.StartsWith("1"))
{
this.textBox1.Text = str.Substring(0, 1);
}
else if (str.StartsWith("5"))
{
this.textBox1.Text = str.Substring(0, 1);
this.textBox2.Text = str.Substring(4, 16);
}
}

Related

C# how to get proper string from GetString()

I use:
propItem.Value = System.Text.Encoding.UTF8.GetBytes(textBox1.Text + "\0");
where textBox1.Text contains "MMM", to set the Value and save it in a file (propItem.Value is byte[]), but when I try to read the file I use:
string myString = System.Text.Encoding.UTF8.GetString(propItem.Value);
and get: "M\0M\0M\0\0\0". Could anybody advice how to get the proper string, without '\0'. I have seen all the answers here regarding the similar problems, but none of the answers worked in my case.
Loading the file:
Image img0 = null;
string sourceFile;
private void btnLoad_Click(object sender, EventArgs e)
{
using (var selectFileDialog = new OpenFileDialog())
{
if (selectFileDialog.ShowDialog() == DialogResult.OK)
{
sourceFile = selectFileDialog.FileName;
img0 = Image.FromFile(sourceFile);
PropertyItem[] propItems = img0.PropertyItems;
textBox1.Text = "Nothing in the file.";
foreach (PropertyItem propItem in propItems)
{
if (propItem.Id == 0x9286)
{
string myString = System.Text.Encoding.UTF8.GetString(propItem.Value);
textBox1.Text = myString ;
}
}
}
}
}
It should be:
string myString = System.Text.Encoding.Unicode.GetString(propItem.Value);

Putting a Struct in a Dictionary [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
i want to use a struct in a dictionary its key is a string and the value is the struct. i don't know what's the syntax as i'm new to c# i was writing c++ before.
BTW i want to read from a text file and put the lines in the dictionary.
here's what i did already:
public class CDinfo
{
public string code;
public string type;
public int count;
}
private void button1_Click(object sender, EventArgs e)
{
string pathsource = #"F:\Computer Science\CD & Instruments\CDs.txt";
CDinfo lolo = new CDinfo();
string name;
name = textBox1.Text;
lolo.type = textBox2.Text;
lolo.code = textBox3.Text;
lolo.count = int.Parse(count.Text);
Dictionary<string, CDinfo> MS = new Dictionary<string, CDinfo>();
StreamReader reader = new StreamReader(pathsource);
while (reader.Peek() != -1)
{
string m;
string[] fasl;
m = reader.ReadLine();
fasl = m.Split(',');
lolo.type = fasl[1];
lolo.code = fasl[2];
lolo.count = fasl[3];
MS.Add(fasl[0], lolo);
}
reader.Close();
StreamWriter sw = new StreamWriter(pathsource, append: true);
string s = name + ',' + lolo.type + ',' + lolo.code + ',' + lolo.count;
sw.WriteLine(s);
sw.Close();
MessageBox.Show("CD Added Successfully.");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}
After running the solution i'm getting this error "Index was outside the bounds of the array".
You are initializing a new dictionary every time you click Button1, and you are not keeping track of it, so you will never be able to use it from a different context. You need to defined your dictionary as a class variable, and add a value to it from inside your click method:
Dictionary<string, CDinfo> MS = new Dictionary<string, CDinfo>(); // initialize the dictionary somewhere outside of your click handler
private void button1_Click(object sender, EventArgs e)
{
CDinfo lolo = new CDinfo();
string name;
name = textBox1.Text;
lolo.type = textBox2.Text;
lolo.code = textBox3.Text;
lolo.count = int.Parse(count.Text);
// add to the dictionary here
MS.Add(name, lolo);
}
Also, as some of the comments have already mentioned, CDinfo should probably be a class, not a struct.

How to read one txt file into several textboxes by a button(in different order)?

For example: if my txt file's contents is aaa|bbb|ccc. I'd like to use a button to distribute aaa to textbox2, bbb to textbox5, cccto textbox3 . So How to make it? I have try lots of ways to solve it ,but it still doesn't work.Please~
if your text file content like this.
aaaa|bbb|cccc
dddd|eee|ffff
then you can try this.
private void button1_Click(object sender, EventArgs e)
{
textBox1.Multiline = true;
textBox2.Multiline = true;
textBox3.Multiline = true;
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
StringBuilder sb3 = new StringBuilder();
var lines = File.ReadAllLines("D:\\sample.txt");
foreach (var line in lines)
{
var splits = line.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (splits.Length > 2) {
sb1.Append(splits[0] + Environment.NewLine);
sb2.Append(splits[1] + Environment.NewLine);
sb3.Append(splits[2] + Environment.NewLine);
}
}
textBox1.Text = sb1.ToString();
textBox2.Text = sb2.ToString();
textBox3.Text = sb3.ToString();
}
out will be like this.

No overload for 'button1_Click' matches delegate

I don't understand why I get this error... Can anyone help me?
private void button1_Click(object sender, EventArgs e, string filePath)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
Filenametext.Text = of.FileName;
//Create an instance for the openbox dialog
//And opens the explorer to select the wanted file.
{
DataRow row;
DataService m_WsData = new DataService();
string XMLFileName = ConfigurationSettings.AppSettings["XMLPath"].ToString() + DateTime.Now.Ticks.ToString() + ".xml";
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding("ISO-8859-1"));
{
DataSet ds = m_WsData.GEDS();
string line = "";
int lineNo = 0;
string lineStart = "";
string lineEnd = "";
string[] fileRow;
{
line = sr.ReadLine();
if (line != null)
{
fileRow = line.Split(new Char[] { ';' });
if (lineNo == 0)
{
lineStart = fileRow[0];
}
if (fileRow[0] != "00" && fileRow[0] != "99")
{
row = ds.Tables["FuelFileData"].NewRow();
row["TransNo"] = fileRow[0];
row["CustomerNo"] = fileRow[1];
row["TruckNo"] = fileRow[2];
row["FuelDate"] = fileRow[3];
row["FuelTime"] = fileRow[4];
row["Place"] = fileRow[5];
row["FuelTypeNo"] = fileRow[6];
row["FuelDescription"] = fileRow[7];
row["DriverNo"] = fileRow[8];
row["Blank"] = fileRow[9];
row["TransType"] = fileRow[10];
row["Fuel"] = fileRow[11];
row["FuelCost"] = fileRow[12];
row["MileageFile"] = fileRow[13];
row["DrivenKm"] = fileRow[14];
row["AverageConsFile"] = fileRow[15];
//row["ImportedGuid"]=fileRow[16];
}
lineEnd = fileRow[0];
lineNo++;
}
} while (line != null);
lineStart = lineStart.Trim() + lineEnd.Trim();
fs.Close();
if (lineStart == "0099")
{
ds.WriteXml(XMLFileName);
System.IO.File.Delete(XMLFileName);
}
}
}
}
Cause
You cannot add parameters on event handler methods.
The Click event is defined as
public event RoutedEventHandler Click;
which means that the handler must match the delegate RoutedEventHandler which is
public delegate void RoutedEventHandler(Object sender, RoutedEventArgs e);
Solution
Remove the string filePath parameter and pass the path via a public property.

WebClient DownloadFile Illegal characters in path

I'm a newbie, so I'm sure this is something really basic that I'm missing.
I have a simple program to run through a csv file that contains links to images to save those images in the specified save file location.
I am parsing the cell that contains the url into a List<string[]>.
If I put GetImage(#"http://www.example.com/picture.jpg", 1) my GetImage function performs as it should. When I try to use the loop and pass in the str[0] variable, I receive an error about illegal characters in path.
I've used a MessageBox to tell me what the difference is and as far as I can tell, when I pass the str[0] into the function it adds double quotes(i.e., "http://www.example.com" is displayed instead of http://www.example.com as it is when I just send the one string.
What am I doing wrong?
private void button2_Click(object sender, EventArgs e)
{
string fileName = textBox1.Text;
folderBrowserDialog1.ShowDialog();
string saveLocation = folderBrowserDialog1.SelectedPath;
textBox2.Text = saveLocation;
List<string[]> file = parseCSV(fileName);
int count = 0;
foreach (string[] str in file)
{
if (count != 0)
{
GetImage(str[0], str[4]);
}
count++;
}
//GetImage(#"http://www.example.com/picture.jpg", "1");
}
private void GetImage(string url, string prodID)
{
string saveLocation = textBox2.Text + #"\";;
saveLocation += prodID + ".jpg";
WebClient webClt = new WebClient();
webClt.DownloadFile(url, saveLocation);
}
No matter which function or method creates these quotes, you could replace them all.
String myUrl = str[0];
myUrl = myUrl.Replace("\"", "");
GetImage(myUrl, str[4]);
I think your files contains the quotes or the parseCSV method creates them.
Update:
I used this code and it works with no problem at all and without quotes:
static void Main(string[] args)
{
string fileName = "Test";
//folderBrowserDialog1.ShowDialog();
string saveLocation = ".\\";
//textBox2.Text = saveLocation;
List<string[]> file = new List<string[]>
{
new string[] { "http://www.example.com", "1", "1", "1", "1"},
new string[] { "http://www.example.com", "2", "2", "2", "2"},
};
int count = 0;
foreach (string[] str in file)
{
if (count != 0)
{
GetImage(str[0], str[4]);
}
count++;
}
//GetImage(#"http://www.example.com/picture.jpg", "1");
}
private static void GetImage(string url, string prodID)
{
string saveLocation = ".\\"; // textBox2.Text + #"\"; ;
saveLocation += prodID + ".jpg";
WebClient webClt = new WebClient();
Console.WriteLine(url);
webClt.DownloadFile(url, saveLocation);
}

Categories