I need to get the name of the button that called the event handler

Advertisements

I am creating an application to load text files into two prompts. I want to be able to edit the rich text box and save that back to the text file.
WinForms Form

The buttons are created through code and are all assigned to one event handler to open a text file corresponding to their name (Preset1.txt would be from button Preset1). I want to get the name of the button and put it into the save button event handler.

The button save event needs to get the name of the button referencing it and send it over to the save button so it can save to the text file selected by said button.

Here is all of my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.Remoting.Channels;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskBand;

namespace Shirohana
{
    public partial class fmMain : Form
    {
        public fmMain()
        {
            InitializeComponent();
        }

        public async void WaitSomeTime(Form item)
        {
            await Task.Delay(3000);
            item.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Set up the prompt text box
            int xPrompt, yPrompt;

            rtbPrompt.Font = lblPrompt.Font;

            pnlPrompt.Width    = rtbPrompt.Width  + 10;
            pnlPrompt.Height   = rtbPrompt.Height + 10;

            xPrompt            = rtbPrompt.Location.X;
            yPrompt            = rtbPrompt.Location.Y;

            pnlPrompt.Location = new Point(xPrompt-5,yPrompt-5);
            lblPrompt.Location = new Point(xPrompt-5,yPrompt-lblPrompt.Height-5);

            int xNegative, yNegative;

            rtbNegative.Font   = lblPrompt.Font;

            pnlNegative.Width  = rtbNegative.Width  + 10;
            pnlNegative.Height = rtbNegative.Height + 10;

            xNegative          = rtbNegative.Location.X;
            yNegative          = rtbNegative.Location.Y;

            pnlNegative.Location = new Point(xNegative - 5, yNegative - 5);
            lblNegative.Location = new Point(xNegative - 5, yNegative - lblNegative.Height - 5);

            ///////////////////////////////////////////////////////////////////////
            ///
            CreateButtons();

        }
        public void MissingPresetError()
        {
            MessageBox.Show("Please make sure Preset text file exists and is placed in the ShirohanaPresets folder.", "Preset File Missing!");
        }

        public void CreateButtons()
        {
            string fpath   = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ShirohanaAi\ShirohanaPresets";
            int fCount     = Directory.GetFiles(fpath, "*", SearchOption.TopDirectoryOnly).Length-1; // REPLACE THE COUNT
            int FileNumber = 1;
            int fileCount = 20-1;
            for (int i = 0; i < fileCount; i++)
            {
                FileNumber++;
                Button newButton = new Button();
                this.Controls.Add(newButton);
                newButton.Text                      = "PST "+FileNumber;
                newButton.Size                      = new Size(105, 50);
                newButton.Font                      = Preset1.Font;
                newButton.FlatStyle                 = FlatStyle.Flat;
                newButton.FlatAppearance.BorderSize = 0;
                newButton.BackColor                 = ColorTranslator.FromHtml("206, 100, 0");
                newButton.ForeColor                 = ColorTranslator.FromHtml("251, 248, 248");
                newButton.Margin                    = new Padding(8, 8, 8, 8);
                newButton.Name                      = "Preset"+FileNumber;
                newButton.Click += new EventHandler(btnPreset_Click);
                newButton.Click += new EventHandler(btnGetID);

                pnlPresets.Controls.Add(newButton);

                // CLEAR TEXT FILE File.WriteAllText(path, String.Empty);

                string create_path = fpath + @"\Preset" + FileNumber + ".txt";
                if (!File.Exists(create_path))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(create_path))
                    {
                        sw.WriteLine("PROMPT HERE - PRESET "+FileNumber);
                        sw.WriteLine("NEGATIVE HERE");
                        // To save a new prompt just delete the file and rewrite it with the text from the textboxes
                    }
                }


            }
            
        }


        private void btnGetID(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
        }

        private void btnPreset_Click(object sender, EventArgs e)
        {
            //Create path for presets
            string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ShirohanaAi\ShirohanaPresets";
            // If directory does not exist, create it
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            Button btn = (Button)sender;

            string textFile = path + @"\"+ btn.Name + ".txt";

            if (File.Exists(textFile))
            {
                string textContent = File.ReadAllText(textFile);
                string[] line = File.ReadAllLines(textFile);

                rtbPrompt.Text = line[0];
                rtbNegative.Text = line[1];

            }
            else
            {
                MissingPresetError();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // How do I get the button name???
            string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ShirohanaAi\ShirohanaPresets";
            string textFile = path + @"\" + btn.Name + ".txt";
        }

        #region Copy Buttons
        private void btnCopyPrompt_Click(object sender, EventArgs e)
        {
            if (rtbPrompt.Text != "")
            { 
                System.Windows.Forms.Clipboard.SetText(rtbPrompt.Text);
                new ToolTip().Show("Copied Prompt Info!",this, rtbPrompt.Location.X + 100 , rtbPrompt.Location.Y, 1000);
            }
            else
            {
                new ToolTip().Show("Empty!", this, rtbPrompt.Location.X + 100, rtbPrompt.Location.Y, 1000);
            }
        }

        private void btnCopyNegative_Click(object sender, EventArgs e)
        {
            if (rtbNegative.Text != "")
            {
                System.Windows.Forms.Clipboard.SetText(rtbNegative.Text);
                new ToolTip().Show("Copied Negative Prompt Info!",this, rtbNegative.Location.X + 170, rtbNegative.Location.Y, 1000);
            }
            else
            {
                new ToolTip().Show("Empty!", this, rtbNegative.Location.X + 170, rtbNegative.Location.Y, 1000);
            }
        }
        #endregion


    }
}

>Solution :

You can store last clicked button’s name in a variable and use it inside other handler in the same form.

  1. Create a new variable in the fmMain class:
public partial class fmMain : Form
{
    private string? lastPresetButtonName;
    // all other code here
}
  1. Save a new value to lastPresetButtonName on btnPreset_Click:
private void btnPreset_Click(object sender, EventArgs e)
{
    lastPresetButtonName = ((Button)sender).Name;
    // other code here
}

  1. Now you can read a button name from btnSave_Click:
private void btnSave_Click(object sender, EventArgs e)
{
    if (lastPresetButtonName != null)
    {
        string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ShirohanaAi\ShirohanaPresets";
        string textFile = path + @"\" + lastPresetButtonName + ".txt";
        // other code here
    }
}

Leave a ReplyCancel reply