Clean short code to show days since button was clicked (Visual C# Winforms)

There are various buttons in my C# winform and for each button press an action is associated with it. I currently have code where when the button is clicked I record the date the button was clicked, then update the button’s Text to show the number of days ago the button was clicked (along with whatever function the button performs).

As days go on, each button will show how many days have elapsed since the button was clicked. My code includes writing to a file, loading the file when the program starts and so on… but I find I have to do a dummy click to get the buttons initialize properly and at the end of the day it is a bit cumbersome to add new buttons with the same ‘days elapsed’ feature…. especially if I haven’t done so in months.

So to cut to my question: ** Is there a simpler, cleaner way of doing this? Maybe even a way to avoid writing to a file??**

I have working code but it’s my usual bad form, uses global variables and I KNOW there must be a simpler cleaner way. Here is an example for “Button 54”

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> private void button54_Click(object sender, EventArgs e)
{
// Global Vars
// gbuttonlogpath path where logfiles are stored for each button
// for each new button do THIS:
// 1) create
// public int gbutton## = 0;
// Need this to differentiate between clicking the button to initialize it (at program start)
// and clicking it afterwards to actually update its days-elapsed value
// 2) copy the common 'button code' to the button's click event
// 3) update the button name in the main if/else code at button.
// 4) call the button's perform click at program start in Form1_Load(object sender, EventArgs e)
// button initializers
//gbutton37 = 0;
//button37.PerformClick();
// string _s = (sender as Button).Text; // the Text on the button face
string _s = (string)(sender as Button).Tag; // the Text/funtionTitle on the button face
string _btnID = (sender as Button).Name; // the name of the button, eg. button17
// string _btnText = _s (tag value set in form load initialization).
string _myfile = gbuttonlogpath + _btnID + ".txt";
if (gbutton54 > 0) //## EDIT ##############################
{
gbutton54++; //## EDIT ################################
// do whatever you want the button to actually do.
some_magical_actions();
//#### code common to each button ######################
tbs.AppendText("rnButton " + _btnID + " TASK.");
string mydaterecorded = DateTime.Now.ToString("dd MMM yyyy"); // eg 29 Jul 2015
// if no record file for this button, create it.
if (!System.IO.File.Exists(_myfile))
{
System.IO.File.WriteAllText(_myfile, mydaterecorded);
}
// read record file for this button and calc days ago it was pressed.
string readText = System.IO.File.ReadAllText(_myfile);
DateTime d1 = DateTime.Parse(readText);
DateTime d2;
//d1 = Convert.ToDateTime(dataGridView1.Rows[i].Cells[2].Value);
d2 = DateTime.Now;
TimeSpan ts = d2 - d1;
System.IO.File.WriteAllText(_myfile, mydaterecorded);
int jj = _s.IndexOf('*');
if (jj < 0) jj = _s.Length - 1;
string _temp = _s.Substring(0, jj);
// update the days elapsed in the button text.
(sender as Button).Text = _temp + "* 0";
}
else
{
TimeSpan ts;
// DateTime _oldDate = new DateTime(2022, 11, 11);
string mydaterecorded = DateTime.Now.ToString("dd MMM yyyy"); // eg 29 Jul 2015 // read record file for this button and calc days ago it was pressed.
if (!System.IO.File.Exists(_myfile))
{
// make the days elapsed some arbitrary large number
ts = new TimeSpan(99, 0, 0, 0, 0);
}
else
{
string readText = System.IO.File.ReadAllText(_myfile);
DateTime d1 = DateTime.Parse(readText);
DateTime d2;
d2 = DateTime.Now;
ts = d2 - d1;
}
// set the button text and 'days since'.
//Button Tag will hold string for button's function
if (_s.Contains("*")) // the Text on the button face
{
int jj = _s.IndexOf('*');
string _temp = _s.Substring(0, jj);
// update the days elapsed in the button text.
(sender as Button).Text = _temp + "* " + ts.Days.ToString();
}
else
{
//generating button text with * followed by days elapsed
(sender as Button).Text = _s + "* " + ts.Days.ToString();
}
// initialize button
gbutton54++;
} // last line before button's ending bracket.
}
</code>
<code> private void button54_Click(object sender, EventArgs e) { // Global Vars // gbuttonlogpath path where logfiles are stored for each button // for each new button do THIS: // 1) create // public int gbutton## = 0; // Need this to differentiate between clicking the button to initialize it (at program start) // and clicking it afterwards to actually update its days-elapsed value // 2) copy the common 'button code' to the button's click event // 3) update the button name in the main if/else code at button. // 4) call the button's perform click at program start in Form1_Load(object sender, EventArgs e) // button initializers //gbutton37 = 0; //button37.PerformClick(); // string _s = (sender as Button).Text; // the Text on the button face string _s = (string)(sender as Button).Tag; // the Text/funtionTitle on the button face string _btnID = (sender as Button).Name; // the name of the button, eg. button17 // string _btnText = _s (tag value set in form load initialization). string _myfile = gbuttonlogpath + _btnID + ".txt"; if (gbutton54 > 0) //## EDIT ############################## { gbutton54++; //## EDIT ################################ // do whatever you want the button to actually do. some_magical_actions(); //#### code common to each button ###################### tbs.AppendText("rnButton " + _btnID + " TASK."); string mydaterecorded = DateTime.Now.ToString("dd MMM yyyy"); // eg 29 Jul 2015 // if no record file for this button, create it. if (!System.IO.File.Exists(_myfile)) { System.IO.File.WriteAllText(_myfile, mydaterecorded); } // read record file for this button and calc days ago it was pressed. string readText = System.IO.File.ReadAllText(_myfile); DateTime d1 = DateTime.Parse(readText); DateTime d2; //d1 = Convert.ToDateTime(dataGridView1.Rows[i].Cells[2].Value); d2 = DateTime.Now; TimeSpan ts = d2 - d1; System.IO.File.WriteAllText(_myfile, mydaterecorded); int jj = _s.IndexOf('*'); if (jj < 0) jj = _s.Length - 1; string _temp = _s.Substring(0, jj); // update the days elapsed in the button text. (sender as Button).Text = _temp + "* 0"; } else { TimeSpan ts; // DateTime _oldDate = new DateTime(2022, 11, 11); string mydaterecorded = DateTime.Now.ToString("dd MMM yyyy"); // eg 29 Jul 2015 // read record file for this button and calc days ago it was pressed. if (!System.IO.File.Exists(_myfile)) { // make the days elapsed some arbitrary large number ts = new TimeSpan(99, 0, 0, 0, 0); } else { string readText = System.IO.File.ReadAllText(_myfile); DateTime d1 = DateTime.Parse(readText); DateTime d2; d2 = DateTime.Now; ts = d2 - d1; } // set the button text and 'days since'. //Button Tag will hold string for button's function if (_s.Contains("*")) // the Text on the button face { int jj = _s.IndexOf('*'); string _temp = _s.Substring(0, jj); // update the days elapsed in the button text. (sender as Button).Text = _temp + "* " + ts.Days.ToString(); } else { //generating button text with * followed by days elapsed (sender as Button).Text = _s + "* " + ts.Days.ToString(); } // initialize button gbutton54++; } // last line before button's ending bracket. } </code>
        private void button54_Click(object sender, EventArgs e)
        {
// Global Vars
// gbuttonlogpath  path where logfiles are stored for each button
// for each new button do THIS:
// 1) create
// public int gbutton## = 0;
//     Need this to differentiate between clicking the button to initialize it (at program start)
//     and clicking it afterwards  to actually update its days-elapsed value
// 2) copy the common 'button code' to the button's click event
// 3) update the button name in the main if/else code at button.
// 4) call the button's perform click at program start in  Form1_Load(object sender, EventArgs e)
// button initializers
//gbutton37 = 0;
//button37.PerformClick();

     // string _s = (sender as Button).Text;    // the Text on the button face
    string _s = (string)(sender as Button).Tag; // the Text/funtionTitle on the button face
            string _btnID = (sender as Button).Name;  // the name of the button, eg.  button17
             //  string _btnText = _s (tag value set in form load initialization).

            string _myfile = gbuttonlogpath + _btnID + ".txt";

            if (gbutton54 > 0) //## EDIT ##############################
            {
                gbutton54++; //## EDIT ################################
        
               // do whatever you want the button to actually do.

                   some_magical_actions();



                //#### code common to each button ######################
                tbs.AppendText("rnButton " + _btnID + " TASK.");
                string mydaterecorded = DateTime.Now.ToString("dd MMM yyyy"); // eg 29 Jul 2015
                // if no record file for this button, create it.
                if (!System.IO.File.Exists(_myfile))
                {
                    System.IO.File.WriteAllText(_myfile, mydaterecorded);
                }
                // read record file for this button and calc days ago it was pressed.
                string readText = System.IO.File.ReadAllText(_myfile);

                DateTime d1 = DateTime.Parse(readText);
                DateTime d2;
                //d1 = Convert.ToDateTime(dataGridView1.Rows[i].Cells[2].Value);
                d2 = DateTime.Now;
                TimeSpan ts = d2 - d1;
                System.IO.File.WriteAllText(_myfile, mydaterecorded);


                int jj = _s.IndexOf('*');
                if (jj < 0) jj = _s.Length - 1;
                string _temp = _s.Substring(0, jj);
                // update the days elapsed in the button text.
                (sender as Button).Text = _temp + "* 0";


            }
            else
            {
                TimeSpan ts;
                // DateTime _oldDate = new DateTime(2022, 11, 11);
                string mydaterecorded = DateTime.Now.ToString("dd MMM yyyy"); // eg 29 Jul 2015                                                               // read record file for this button and calc days ago it was pressed.
                if (!System.IO.File.Exists(_myfile))
                {
                    // make the days elapsed some arbitrary large number
                    ts = new TimeSpan(99, 0, 0, 0, 0);
                }
                else
                {
                    string readText = System.IO.File.ReadAllText(_myfile);
                    DateTime d1 = DateTime.Parse(readText);
                    DateTime d2;
                    d2 = DateTime.Now;
                    ts = d2 - d1;
                }
                // set the button text and 'days since'.  
                 //Button Tag will hold string for button's function
                if (_s.Contains("*"))    // the Text on the button face
                {
                    int jj = _s.IndexOf('*');
                    string _temp = _s.Substring(0, jj);
                    // update the days elapsed in the button text.
                    (sender as Button).Text = _temp + "* " + ts.Days.ToString();
                }
                else
                {
                    //generating button text with * followed by days elapsed
                    (sender as Button).Text = _s + "* " + ts.Days.ToString();
                }

                // initialize button
                gbutton54++;  
            } // last line before button's ending bracket.
        }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật