How to use a MessageBox in a function - c#

I am trying to get function to take in two strings and show message box:
public void Myfunction (string str1, string str2)
{
MessageBox.Show("your message was " + str1 + Environment.NewLine + str2);
}
private void Btn_Display_Click(object sender, RoutedEventArgs e)
{
string today;
today = DateTime.Now.ToString("dd/MM/yyyy");
myfunction(TextBox_Msg.Text, today);
}

It's not clear what's going on, say, what myfunction is supposed to do? Functions compute values.
I suggest showing message in one go:
private void Btn_Display_Click(object sender, RoutedEventArgs e) {
// Show message - MessageBox.Show
// of several lines - string.Join(Environment.NewLine
// 1st line "your message was" + TextBox_Msg.Text
// 2nd line DateTime.Now in "dd/MM/yyyy" format
MessageBox.Show(string.Join(Environment.NewLine,
$"your message was {TextBox_Msg.Text}",
DateTime.Now.ToString("dd/MM/yyyy")));
}
If you insist on extracting method then, let's first rename it - ShowMessageLines:
// Let's show arbitrary many lines (whe only 2?)
// Let's accept all types (not necessary strings)
public static void ShowMessageLines(params object[] lines) {
// public method - input arguments validation
if (null == lines)
throw new ArgumentNullException(nameof(lines));
// Combine all lines into textToShow
// First line must have a prefix - "your message was "
string textToShow = string.Join(Environment.NewLine, lines
.Select((text, index) => index == 0
? $"your message was {text}"
: text?.ToString()));
MessageBox.Show(textToShow);
}
...
private void Btn_Display_Click(object sender, RoutedEventArgs e) {
ShowMessageLines(
TextBox_Msg.Text,
DateTime.Now.ToString("dd/MM/yyyy"));
}

Related

C# insert text after each occurence of a text string using wildcards [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Solved:
This solution has been solved. I was modding a game and am creating a C# windows form to easily manipulate large quantities of repeating data, or expressions, and quickly insert mass changes to a file, or files. I was stuck on identifying a regular expression with Regex in my data files and inserting a text box field of data right after the expression I identified. The expression I have works in the regex editor, thanks to #Kris, but when I deployed it into my program, nothing happened. I apologize for not having my thoughts in order, I will be sure to be more clear next time I use SO.
Below is the data I wanted to manipulate, followed by the working code I was able to fix myself with pointers from #Kris and #Rufus L. Again, I needed to search for particular data strings and insert a new string underneath the data property in every occurrence in the file. Hope this helps someone.
The data properties text looks like this:
1234 = {
workers = {
culture = dudes
religion = awesome
size = 37800
}
professionals = {
culture = dudes
religion = awesome
size = 6000
}
leaders = {
culture = dudes
religion = awesome
size = 500
}
}
1235 = {
workers = {
culture = dudes
religion = awesome
size = 37800
}
professionals = {
culture = dudes
religion = awesome
size = 6000
}
leaders = {
culture = dudes
religion = awesome
size = 500
}
}
I only want to insert text into the parent #### = {} property that holds the child = {} property fields. IE, I want to insert textBox2.Text in a new line under 1234 = {
I have the regex expression linked on here, thanks to #Kris.
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
static string[] files;
static int curNum = 0;
static string[] txtFiles;
static string[] provinces;
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
System.IO.File.WriteAllText(pathText.Text + txtFiles[curNum], richTextBox1.Text);
}
private void prevButton_Click(object sender, EventArgs e) {
if(curNum > 0)
curNum--;
richTextBox1.Text = System.IO.File.ReadAllText(pathText.Text + txtFiles[curNum]);
filenameLabel.Text = txtFiles[curNum];
}
private void loadButton_Click(object sender, EventArgs e) {
curNum = 0;
txtFiles = GetFileNames(pathText.Text, "*.txt");
richTextBox1.Text = System.IO.File.ReadAllText(pathText.Text + txtFiles[curNum]);
filenameLabel.Text = txtFiles[curNum];
}
static string[] GetFileNames(string path, string filter) {
files = Directory.GetFiles(path, filter);
for (int i = 0; i < files.Length; i++)
files[i] = Path.GetFileName(files[i]);
return files;
}
private void nextButton_Click(object sender, EventArgs e) {
if(curNum < txtFiles.Length)
curNum++;
richTextBox1.Text = System.IO.File.ReadAllText(pathText.Text + txtFiles[curNum]);
filenameLabel.Text = txtFiles[curNum];
}
private void appendButton_Click(object sender, EventArgs e)
{
provinces = Regex.Matches(richTextBox1.Text, #"\d+(.*?){")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
for (int i = 0; i < provinces.Length; i++)
{
richTextBox1.Text = richTextBox1.Text.Replace(provinces[i], provinces[i] + System.Environment.NewLine + " " + textBox2.Text);
}
}
}
}
Use regex
\d+(.*?){
tested here
Another way to do it would be to insert the text at the end of each block, by searching for two } characters separated by 0 or more whitespace characters. The regex for this would look like:
Regex.Matches(searchString, "}\\s}");
In either case, when inserting the strings we should start from the last match (at the end of the string) and move backwards towards the beginning, because each insert will change the string length and therefore impact the index at which we want to do the insertion.
For example:
/// <summary>
/// Returns a string with newText inserted into parentText
/// </summary>
/// <param name="newText">The new text to insert</param>
/// <param name="parentText">The parent text to insert into</param>
/// <returns>The parent string with the newText inserted</returns>
private string GetInsertedText(string newText, string parentText)
{
var newParentText = parentText;
var matches = Regex.Matches(newParentText, "}\\s}");
// Replace from the last occurrence, since each insert will
// change the length of our string and alter the insert location
for(int index = matches.Count - 1; index >= 0; index--)
{
var match = matches[index];
newParentText = newParentText.Substring(0, match.Index + 1) +
Environment.NewLine + newText +
newParentText.Substring(match.Index + 1);
}
return newParentText;
}
You also might want to create a method that adds 4 spaces to the beginning of each line of the textBox1.Text so that it has a proper indent after it's inserted. For example:
private string GetIndentedText(string originalText, string indentText = " ")
{
return $"{indentText}{originalText}".Replace("\n", $"\n{indentText}").TrimEnd();
}
The usage of this would look something like:
private void button1_Click(object sender, EventArgs e)
{
// Check for any text requirements here (like it should contain
// an open brace, an equals sign, end with a close brace, etc.)
if (textBox1.Text.Length > 0)
{
// Insert the new (indented) text into our RichTextBox
richTextBox1.Text = GetInsertedText(GetIndentedText(textBox1.Text),
richTextBox1.Text);
// Clear the input textbox
textBox1.Text = "";
}
}

Trim textbox text after 20 characters used and spaces if contains spaces

I have a WinFormApp with 2 txtboxes (LongName and ShortName) with a Button.
When txt is entered in the LongName txtbox, I want to press the button to shorten all txt inside LongName txtbox to the first 20 characters imput and to remove any spaces within' the txtbox then display the results in the ShortName txtbox. I'm having a real hard time trying to get this correct. I've tried a number of ways to try but ultimately can't seem to get it right. Here is example code:
private void btnGetSN_Click(object sender, EventArgs e)
{
Regex space = new Regex(#" ");
MatchCollection spacematch = space.Matches(txtLongName.Text);
if (txtLongName.Text.Length > 20)
{
string toTrim = txtLongName.Text;
toTrim = toTrim.Trim();
txtShortName.Text = ("'" + toTrim.ToString() + "'");
}
if (spacematch.Count > 0)
{
txtLongName.Text.Replace(" ", "");
}
}//closes method
I've been able to limit the txtbox to only 20 characters in the properties but I would like to setup a If variable to allow more customization.
Am I on the right track?
No errors in the code but when executing the button, nothing happens. Any help is appreciated.
string.Replace() doesn't update the string itself, but rather returns a new string that is modified.
private void btnGetSN_Click(object sender, EventArgs e)
{
// remove space from txtLongName
txtLongName.Text = txtLongName.Text.Replace(" ", string.Empty);
// take only the first 20characters from txtLongName
txtShortName.Text = txtLongName.Text.Substring(0, Math.Min(txtLongName.Text.Length, 20));
}
EDIT: Previous code will remove space from txtLongName. If that is not intended, use this instead :
private void btnGetSN_Click(object sender, EventArgs e)
{
// remove space from txtLongName
var name = txtLongName.Text.Replace(" ", string.Empty);
// take only the first 20characters from txtLongName
txtShortName.Text = name.Substring(0, Math.Min(name.Length, 20));
}
Looks like you need to write differently
private void button1_Click(object sender, EventArgs e)
{
var shortName = txtLongName.Text.Trim().Replace(" ", "");
var maxLength = (shortName.Length > 20) ? 20 : shortName.Length;
if(txtLongName.Text.Trim().Length > 0)
txtShortName.Text = shortName.Substring(0, maxLength);
}

Seperate a label into 2 different Textbox C#

I wanted to know how i could split this label into 2 different textboxes. Before writing here i searched google and came this far, but now both of my textboxes is showing the value 1000. The program is supposed to split the numbers between the x.
Example: Left textbox = 80 & Right textbox = 1000. What am I missing?
private void Split_btn_Click(object sender, EventArgs e)
{
string s = label1.Text;
// Split string on spaces.
// ... This will separate all the words.
string[] words = s.Split('x');
foreach (string word in words)
{
Left_txtbox.Text = word;
Right_Textbox.Text = word;
}
}
The problem is the loop. You are setting both textboxes with the same value and overwriting it with every iteration so the last values wins.
You could simply assign the values like follows:
Left_txtbox.Text = words[0];
Right_Textbox.Text = words[1];
I would add the trim() command in as well because you will end up with a space after the 80 and before the 1000.
private void button1_Click(object sender, EventArgs e)
{
string s = label1.Text;
string[] words = s.Split('x');
Left_txtbox.Text = words[0].Trim();
Right_Textbox.Text = words[1].Trim();
}
or add the split directly into the textbox assign
private void button1_Click(object sender, EventArgs e)
{
string s = label1.Text;
Left_txtbox.Text = s.Split('x')[0].Trim();
Right_Textbox.Text = s.Split('x')[1].Trim();
}
Try this instead of your foreach loop:
if (words.Length > 1)
{
Left_txtbox.Text = words[0];
Right_Textbox.Text = words[1];
}

Conversion program storing information in array and using a combobox

This is homework (I always try to point that out so it's up front). The program is a conversion program. The user picks a conversion option from a combo box and then enters a length (ie: Feet to meters) when the user hits calculate the program calculates the conversion. I have several questions because the array part is confusing me. I wanted to make sure I am going in the right direction.
I think I am using my array to populate my combo box (I used an example provided although I do not fully understand it). When the user hits the calculate button should I be storing my conversion values in the same array? something like:
string [,] conversions = { {kilometers to miles, .11111}, {miles to kilometers, .11111}}
Or am I heading in the right direction with what I have? To be clear as it is coded the array populates my combobox so if I add the extra data then it will display those numbers in the combobox, which isn't really what I am going for.
My next question, when the user hits calculate button how is it going to know what option the user has selected? I think it has something to do with index but I'm confused as far as what is actually declaring it?
*****Disregard this question. I think I found an answer*********
Answer on Updating Labels
Finally I think my last question is the page has labels next to the textboxes so if the user chooses 'Miles to kilometers" the entry textbox is going to say Miles and then the answer textbox would say Kilometers... What is that called? I need to find it in my book and cannot. I know I'm missing something but I'm trying to find either an example or where in the book it was covered and I'm simply not seeing it.
Below is my code that I currently have.
public partial class FrmConversions : Form
{
const double Miles_To_Kilometers = 1.6093;
const double Kilometers_To_Miles = 0.6214;
const double Feet_To_Meters = 0.3048;
const double Meters_To_Feet = 3.2808;
const double Inches_To_Centimeters = 2.54;
const double Centimeters_To_Inches = 0.3937;
public FrmConversions()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void FrmConversions_Load(object sender, EventArgs e)
{
cboConversions.Items.Clear(); //clear the combobox
string[,] conversions =
{
{"Kilometers to Miles" , "Miles to Kilometers"},
{"Feet to Meters" , "Meters to Feet"},
{"Inches to Centimeters", "Centimeters to Inches"}
};
foreach (string str in conversions)
{
cboConversions.Items.Add(str);
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtEntry.Clear();
txtAnswer.Clear();
}
public bool IsDecimal(TextBox txtEntry, string name)
{
try
{
Convert.ToDecimal(txtEntry.Text);
return true;
}
catch (FormatException)
{
MessageBox.Show(name + " must be a decimal value.", "Entry Error");
txtEntry.Focus();
return false;
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
int index = cboConversions.SelectedIndex;
if (index != -1)
{
try
{
if (IsDecimal())
{
txtAnswer.Text = ToString;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" +
ex.GetType().ToString() + "\n" +
ex.StackTrace, "exception");
}
}
}
}
}
}
There are many ways to do this, a Dictionary would be neat?
In this example, the Keys of the dictionary (the strings I specified) are loaded into the combo box. Later, those strings can be used to retrieve the conversion value from the dictionary.
// Declare at the top
Dictionary<string, double> conversions = {
{ "Kilometers to Miles", Kilometers_To_Miles},
{ "Miles to Kilometers", 1 / Kilometers_To_Miles},
{ "Feet to Meters", Feet_To_Meters},
{ "Meters to Feet", 1 / Feet_To_Meters},
etc
};
// In Form Load
foreach (string str in conversions.Keys)
{
cboConversions.Items.Add(str);
}
// In btnCalculate_Click
var conversionValue = conversions[cboConversions.Text];
var convertedValue = (double)txtEntry.Text * conversionValue; // Need to validate is numeric
txtAnswer.Text = convertedValue
If you were hellbent on using arrays then this would work too, but cheats by using LINQ at the end:
// Declare at the top
object[,] conversions = {
{ "Kilometers to Miles", Kilometers_To_Miles},
{ "Miles to Kilometers", 1 / Kilometers_To_Miles},
{ "Feet to Meters", Feet_To_Meters},
{ "Meters to Feet", 1 / Feet_To_Meters},
etc
};
// In Form Load
foreach (string str in conversions)
{
cboConversions.Items.Add(str[0]);
}
// In btnCalculate_Click
var conversionValue = conversions.First(x => x[0] == cboConventions.Text)[1];
var convertedValue = (double)txtEntry.Text * conversionValue; // Need to validate is numeric
txtAnswer.Text = convertedValue

How to remove blank lines from a C# List<string>?

I am trying to create a routine in C# that sorts a list added to a Multi-Line text box. Once that is done, there is an option to remove all blank lines. Can someone tell me how I would go about doing this? here is what I have so far, but it doesn't work at all when I select the box and click sort:
private void button1_Click(object sender, EventArgs e)
{
char[] delimiterChars = { ',',' ',':','|','\n' };
List<string> sortBox1 = new List<string>(textBox2.Text.Split(delimiterChars));
if (checkBox3.Checked) //REMOVE BLANK LINES FROM LIST
{
sortBox1.RemoveAll(item => item == "\r\n");
}
textBox3.Text = string.Join("\r\n", sortBox1);
}
If you're splitting the string on '\n', sortBox1 won't contain a string containing \n. I would just use String.IsNullOrWhiteSpace, though:
sortBox1.RemoveAll(string.IsNullOrWhiteSpace);
You forgot to sort the lines:
sortBox1.Sort();
A blank line is not "\r\n", that is a line break. Blank lines are empty strings:
sortBox1.RemoveAll(item => item.Length == 0);
You can also remove the blank lines when splitting the string:
private void button1_Click(object sender, EventArgs e) {
char[] delimiterChars = { ',',' ',':','|','\n' };
StringSplitOptions options;
if (checkBox3.Checked) {
options = StringSplitOptions.RemoveEmptyEntries;
} else {
options = StringSplitOptions.None;
}
List<string> sortBox1 = new List<string>(textBox2.Text.Split(delimiterChars, options));
sortBox1.Sort();
textBox3.Text = string.Join("\r\n", sortBox1);
}

Categories