I have created 2 text boxes that take the name and email address, stores it in a "text" file and display the contents in a list box. I have everything done but when it displays in the list box this is the output that I get.
"System.Windows.Forms.TextBox, Text: tony"
"System.Windows.Forms.TextBox, Text: tony#tony.com"
Can anyone tell me why it is doing that please? I'm still new to c# and I know this is a minor thing I just do not know where to look
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace _iLab_Week7
{
public partial class Form1 : Form
{
private StreamReader inFile; //streamreader for input
private StreamWriter outFile; //streamwriter for output
const string filename = "contacts.txt";
public Form1()
{
InitializeComponent();
}
private void btnAddContact_Click(object sender, EventArgs e)
{
//Disable the "add contact" and "email"
btnAddContact.Enabled=false;
txtBoxEmail.Enabled=false;
//check for and create contacts.txt file
if(!File.Exists(filename))
File.Create(filename);
if(File.Exists(filename))
{
try
{
//create the file stream
outFile = new StreamWriter(filename, true);
//get the item from the name and email text box
//write it to the file
outFile.WriteLine(txtBoxName);
outFile.WriteLine(txtBoxEmail + "\n");
//close the file
outFile.Close();
//clear the textbox
txtBoxName.Text="";
txtBoxEmail.Text="";
//the cursor in the text box
txtBoxName.Focus();
txtBoxEmail.Focus();
}
catch (DirectoryNotFoundException exc)
{
lstBoxContact.Items.Add(exc.Message);
}
catch (System.IO.IOException exc)
{
lstBoxContact.Items.Add(exc.Message);
}
string listItem;
this.lstBoxContact.Items.Clear();
btnAddContact.Enabled = false;
try
{
//open file for reading
inFile=new StreamReader(filename);
//read from file and add to list box
while ((listItem=inFile.ReadLine()) !=null)
{
this.lstBoxContact.Items.Add(listItem);
}
//Close the file
inFile.Close();
}
catch (System.IO.IOException exc)
{
this.lstBoxContact.Items.Add(exc);
}
}
else
{
this.lstBoxContact.Items.Add("File Unabailable");
}
}
private void lstBoxContact_SelectedIndexChanged(object sender, EventArgs e)
{
//enable button
btnAddContact.Enabled = true;
txtBoxName.Enabled = true;
txtBoxEmail.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosedEventArgs e)
{
//make sure files are closed
try
{
inFile.Close();
outFile.Close();
}
catch { }
}
}
Replace
outFile.WriteLine(txtBoxName);
outFile.WriteLine(txtBoxEmail + "\n");
with
outFile.WriteLine(txtBoxName.Text);
outFile.WriteLine(txtBoxEmail.Text + "\n");
and try...
ADDED : When you say txtBoxName, you are referring to the txtBoxName object as a whole, which contains many properties - like Text, ForeColor, Font etc.... To get only the value or content, you need to specify the property which gives you that - which is the Text property
More about TextBox
outFile.WriteLine(txtBoxName);
is equivalent to
outFile.WriteLine(txtBoxName.ToString());
For most classes, the ToString() method is the same as Object.ToString(). This method just displays the name of the type of the instance you're trying to display. So you might have only seen
System.Windows.Forms.TextBox
However, the TextBox class helpfully overrides this method and displays both the type name and the value of the Text property.
But as Saagar Elias Jacky said. This is not what you actually intended to do, so just display txtBoxName.Text as he suggested.
Related
This is my first question in Stackoverflow
I am trying to convert some files(.txt,.mp3,.mp4,.pdf,.png,.exe etc.) in a folder to a format .rjb, created by me. And I also want to recover the original files from the .rjb files. But every files other than .txt files get corrupted. Please help me, to accomplish this. The below code is what I am using.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace rjbformat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
//string data = Convert.ToString(File.ReadAllBytes(textBox1.Text));
// string datas = File.ReadAllText(textBox1.Text);
//string dat = File.ReadAllText(textBox1.Text, Encoding.ASCII);
//var dataS = Convert.ToString(datas);
using (StreamWriter sw = new StreamWriter(textBox1.Text + ".rjb"))
{
sw.Write(textBox3.Text);
}
}
catch (Exception)
{
MessageBox.Show("Specified Input file DOESNOT EXIST!", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
//throw;
}
}
else
{
MessageBox.Show("Please select Input file");
}
}
private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Open Text File (Rajib)";
openFileDialog1.Filter = "Text Files(*.txt;*.cod;*.ubc)|*.txt;*.cod;*.ubc";
openFileDialog1.Filter = "All Files(*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
textBox2.Text = openFileDialog1.FileName + ".rjb";
File.Copy(textBox1.Text, textBox2.Text,true);
FileAccess.ReadWrite.ToString(textBox1.Text);
var lines = File.ReadAllLines(textBox1.Text);
/* foreach (string line in lines)
{
textBox3.Text += line+"\r\n";
}*/
File.AppendAllLines(textBox2.Text, lines);
// FileStream fs = new FileStream(textBox1.Text, FileMode.Open);
// int hexIn;
// String hex = "";
// for (int i = 0; i<50/*(hexIn = fs.ReadByte()) != -1*/; i++)
// {
// hex = string.Format("{0:X2}", fs.ReadByte());
// // int bina = fs.ReadByte();
// textBox3.Text += hex;
//}
}
}
}
}
If all you are doing is storing one or more files into your .rjb format and want to get them back intact, this sounds a lot like creating archive files. In that case, you may want to consider just using a standard zip file and customize the extension.
Here's an example using the ZipArchive class:
using System.IO.Compression;
namespace CustomZip
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.rjb";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
You will need to add a reference to System.IO.Compression.FileSystem to your project.
I have a winform, that takes a number of params, executes an stored procedure and then populates a DataGridView with the results.
What I'd like to do is add a string the bottom of my winform that returns a message, including a count of total rows returned.
This presently works fine, using the following syntax :
deskSearchResultCount.Text = String.Format("Your search returned {0} results", deskDataGridView.RowCount );
However as the majority of my application has been written out in the initial form, I was moving sections into classes, to 'tidy it up' a bit - (I'm still very new to c# so apologies if this is a n00b mistake)
Once I add a class called Summary, I would like to call my RowCount as follows :
Summary Returned = new Summary();
deskSearchResultCount.Text = String.Format("Your search returned {0} results", Returned.Total("Desk"));
With my Summary class containing the following :
public class Summary : ContactAnalysisToolbox
{
public int Total(string type)
{
if (type == "Desk")
{
return deskDataGridView.Rows.Count;
}
else
{
return visionDataGridView.Rows.Count;
}
}
However the returned count is always 0. When stepping through the process also, at no point does it appear to be attempting to set itself as anything different.
Can anyone please help / point me in the right direction?
Thanks.
Edit -
I've included the full form also -
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.DirectoryServices.AccountManagement;
using System.IO;
//
// Todo :
// -- Capture Assigned Team In Output
//
//
namespace CallsAnalysisToolbox
{
public partial class ContactAnalysisToolbox : Form
{
public ContactAnalysisToolbox()
{
InitializeComponent();
// Grabs username for current user and displays a welcome message
this.welcomeMessage.Text = "Welcome " + UserPrincipal.Current.Name;
}
private void searchVision_Click(object sender, EventArgs e)
{
try
{
// Run sp_incomingCalls on SQLCLUSTER
this.rep_IncomingCallsTableAdapter.Fill(this.visionReportsDataSet.Rep_IncomingCalls, dateTimePicker1.Value, dateTimePicker2.Value, textBox1.Text, textBox2.Text);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
// Make export button active when search returns results
exportVisionButton.Enabled = (visionDataGridView.Rows.Count > 0);
// Assign returned row count to visionSearchResultCount label and then display label
visionSearchResultCount.Text = String.Format("Your search returned {0} results", visionDataGridView.RowCount);
visionSearchResultCount.Visible = true;
}
private void searchDesk_Click(object sender, EventArgs e)
{
try
{
// Run sp_caseActivity on SQLCLUSTER
this.rPT_CaseActivityTableAdapter.Fill(this.deskDataSet.RPT_CaseActivity, deskFrom.Value, deskTo.Value, deskClientList.Text, deskBenefitList.Text, deskStatusList.Text);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
if (deskDataGridView.Rows.Count > 0)
{
exportDeskButton.Enabled = true;
deskSearchResultCount.Visible = true;
Summary Returned = new Summary();
deskSearchResultCount.Text = String.Format("Your search returned {0} results", Returned.Total("Desk"));
deskSummaryData.Visible = true;
noDataDesk.Visible = false;
// Populate the summary tab
// Get Email / Phone case count
deskTotalCaseResults.Text = deskDataGridView.RowCount.ToString();
//deskTotalEmailCasesResults.Text = emailCount.ToString();
//deskTotalPhoneCasesResults.Text = phoneCount.ToString();
}
}
//TODO : Combine Export functions. Ideally just a single function rather than the repeated logic within the Export class for each datagrid
private void exportVisionButton_Click(object sender, EventArgs e)
{
Export Export = new Export();
Export.ReturnedResult("Vision");
}
private void exportDeskButton_Click(object sender, EventArgs e)
{
Export Export = new Export();
Export.ReturnedResult("Desk");
}
private void deskDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
// Limit 'open case in browser' action to first cell
if (deskDataGridView.CurrentCell.ColumnIndex.Equals(0))
{
string url = string.Format("https://qa.internal.local/agent/case/{0}", deskDataGridView.Rows[e.RowIndex].Cells[0].Value);
Process.Start(url);
}
}
}
}
For example you could do something like this. It's called Method Extension
Try this
public static class Helpers
{
public static string ToTotalCount(this DataGridView item)
{
return string.Format("Your search returned {0} results", item.Rows.Count);
}
}
In your form make sure that the namespace of the class Helpers is in the usings:
deskSearchResultCount.Text = deskDataGridView.ToTotalCount();
Does anyone know how to edit text inside textbox after reading text from raw byte with specific encoding?
Only key that seems to be allowed are: Home, End, Page Up/Down, Delete...
If you try to press any key like: A-Z it won't show up, text box is behaving like Key-down event was overridden somewhere with e.Suppress set to true.
Code:
`
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
byte[] _buffer;
public Form1()
{
InitializeComponent();
Text = "Encoding (Test)";
textBox1.Text = "1252"; // Western European (Windows)
}
private void button1_Click(object sender, EventArgs e)
{
if (_buffer == null)
{
MessageBox.Show("Select file to read from!");
buttonOpenFile_Click(null, null);
return;
}
var encoding = Encoding.GetEncoding(int.Parse(textBox1.Text));
textBox2.Text = encoding.GetString(_buffer);
}
private void buttonOpenFile_Click(object sender, EventArgs e)
{
using (var of = new OpenFileDialog())
{
if (of.ShowDialog() == DialogResult.OK)
{
Text = of.SafeFileName;
ReadToBuffer(of.FileName);
}
}
}
private void ReadToBuffer(string file)
{
using (var fileIO = new FileStream(file, FileMode.Open, FileAccess.Read))
{
_buffer = new byte[fileIO.Length];
fileIO.Read(_buffer, 0, (int)fileIO.Length);
}
}
}
}
`
Click here to download
It appears the file you are attempting to open is larger than the TextBox.MaxLength. I was able to reproduce the issue by creating a simple text file filled with random characters exceeding the MaxLength of the TextBox control.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Cameron_PickerillTrinitapoli_Assn1
{
public partial class seasonalBttnChanger : Form
{
public seasonalBttnChanger()
{
InitializeComponent();
}
//Triggers when program first loads
//Sets up
private void bttnChanger_Load(object sender, EventArgs e)
{
List<Button> lstTxt = new List<Button>
{
bttnSpring, bttnSummer, bttnAutumn, bttnWinter
};
//Wiring up event handlers in run time
foreach (Button txt in lstTxt)
{
txt.MouseEnter += button_MouseEnter;
txt.MouseLeave += button_MouseLeave;
}
}
// Sets up different background colors for TextBoxes
//* Static values for the color of each button need
//to be added.
//**Not what I was trying to accomplish
//**This needs to go somewhere else
void button_MouseEnter(object sender, EventArgs e)
{
try
{
// Event handlers always pass the parameter "sender" in as an object.
// You have to downcast it back to the actual type.
String bttnName = null;
String bttnNameSpring = "Spring";
String bttnNameSummer = "Summer";
String bttnNameAutumn = "Autumn";
String bttnNameWinter = "Winter";
Button txt = (Button)sender;
// stkColor.Push(txt.BackColor);
//txt.BackColor = Color.Red;
bttnName = txt.Name;
if (bttnName == bttnNameSpring)
{
txt.BackColor = Color.LightGreen;
}
else if (bttnName == bttnNameSummer)
{
//txt.BackColor = Color.Red;
txt.BackColor = Color.Red;
}
else if (bttnName == bttnNameAutumn)
{
txt.BackColor = Color.Yellow;
}
else if (bttnName == bttnNameWinter)
{
txt.BackColor = Color.Cyan;
}
}
catch (Exception ex)
{
MessageBox.Show("Error:\n " + ex.Message);
}
}
//Handler for mouse leaving the button
void button_MouseLeave(object sender, EventArgs e)
{
try
{
Button txt = (Button)sender;
//txt.BackColor = stkColor.Pop();
}
catch (Exception ex)
{
MessageBox.Show("Error:\n " + ex.Message);
}
}
}
}
}
Alright, so I'm just trying to create a simple program that changes the background colors of these buttons to some plain colors when you mouse over them. I had the same thing working using TextBox, but I need to get it working with button. I changed everything over to use the Button class, and it seems to have all the same functionality, but now the program runs, but nothing happens when you mouse over the buttons.
I'm pretty new to c#, stack exchange, and only slightly less so to programming in general, so sorry if I'm dinking up on etiquette/formatting my questions, etc.
I think you are trying to reference your buttons title when you are actually calling the button name
Changing:
String bttnName = null;
String bttnNameSpring = "Spring";
String bttnNameSummer = "Summer";
String bttnNameAutumn = "Autumn";
String bttnNameWinter = "Winter";
Button txt = (Button)sender;
To:
String bttnName = null;
String bttnNameSpring = "bttnSpring";
String bttnNameSummer = "bttnSummer";
String bttnNameAutumn = "bttnAutumn";
String bttnNameWinter = "bttnWinter";
Causes the code to work.
If you do infact want to use the "Spring", "Summer" etc reference than i would suggest changing
bttnName = txt.Name;
to
bttnName = txt.Text;
And ensure that the Text of the labels is set correctly
I'm a real noob to C# trying to write a small XML replacer program based on a short code a friend of mine used in one of his apps..
I'm having trouble with this line:
StreamReader sr = new StreamReader(textBox1.Text);
I get an error: "Empty path name is not legal."
why doesn't this work?
the code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ReplaceMe
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
StreamReader sr = new StreamReader(textBox1.Text);
StreamWriter sw = new StreamWriter(textBox1.Text.Replace(".", "_new."));
string cur = "";
do
{
cur = sr.ReadLine();
cur = cur.Replace(textBox2.Text, textBox3.Text);
sw.WriteLine(cur);
}
while (!sr.EndOfStream);
sw.Close();
sr.Close();
MessageBox.Show("Finished, the new file is in the same directory as the old one");
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = openFileDialog1.FileName;
}
}
}
}
Thanks in advance :)
That is because your textBox1 doesn't contain text at the moment you create StreamReader. You set textBox1 text in button1_Click, so you have to create StreamReader in that method.
You should make sure the file exists before you try to access it, it seems you deliver an empty string as a filename.
try accessing the file only when:
if (File.Exists(textBox1.Text))
{
//Your Code...
}
the value of textbox1 is null or empty. also, if you want to manipulate xml look into the objects of the System.Xml namespace. These objects are designed specifically for working with XML.
it's because you're setting an empty string in StreamReader constructor.
I recommend you do a simple validation before read file.
as this:
string fileName = textBox1.Text;
if(String.IsNullOrEmpty(fileName)) {
//textbox is empty
} else if(File.Exists(fileName)) {
//file not exists
} else {
// read it
StreamReader sr = new StreamReader(fileName);
//..
}
Note: it is not right way to manipulate xml files.
check out the XML documentation for more info.