3 Replies - 602 Views - Last Post: 16 July 2011 - 11:51 PM Rate Topic: -----

#1 zel2zel  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 19-September 09

Disabling and enabling buttons

Posted 01 July 2011 - 09:09 AM

I need help for enabling and disabling buttons in my application.
Before information is loaded from a txtfile, the buttons should be disabled first.
It will only be enabled if the txtfile is already loaded and the first letter in the first index of the txtfile (which is contact's nickname) matches the button's letter.


Here's my code for the contact information application:

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;
using System.Reflection;

namespace Version1
{
    public partial class Form1 : Form
    {
        List<string> contactList = new List<string>();
        Button button;

        public Form1()
        {

            InitializeComponent();
            //generate 26 buttons A-Z
            int locX = 10, locY = 30;
            string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            
            for (int i = 0; i < 26; i++)
            {
                button = new Button();
                //  button.Name = alphabet[i].ToString()/* + "_button"*/;
                button.Size = new Size(30, 30);
                button.Location = new Point(locX, locY);
                button.Text = alphabet[i].ToString();
                this.Controls.Add(button);

                button.Enabled = false;
                button.Click += new EventHandler(button_Click);

                locX += 35;

                if (i == 12)
                {
                    locY = 65;
                    locX = 10;
                }
            }
        }
     private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr = openFileDialog1.ShowDialog();
     
            if (dr == DialogResult.OK)
            {
                openFileDialog1.Filter = "Text Files(*.txt) |*.txt";
                string file = openFileDialog1.FileName;
                listBox1.Items.Clear();
                contactList.Clear();
            try
                {
                    StreamReader sr = new StreamReader(file);

                    while (true)
                    {
                        string line = sr.ReadLine();

                        if (line == null)
                        {
                            break;
                        }
                        else
                        {
                            
                            contactList.Add(line);
                            string nickname = line.Split('|')[0];
                            string first = nickname.Substring(0, 1).ToUpper();
                            //im thinking of putting the enable/disable button method here but i dont know how. i already tried something like this:

                            if (first==button.Text.ToString()){
                                button.Enabled = true;
                            } else {
                                button.Enabled = false;
                            }
                         //the problem i encountered by using this code is that the last letter which is Z (doesnt have corresponding nicknames under it) is the only one that was disabled. i tried looping like this:
                        //    for ( int i = 1; i < contactList.Count; i++)
                         //   { split nickname, get the first letter
                          //       if true: enable button letter, else disable
                        //     }
                      //    still, it didn't work :<
                        }
                    }
                }
                catch (Exception e1)
                {
                    MessageBox.Show(e1.Message, "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }


        private void button_Click(object sender, EventArgs e)
        {
            if (sender is Button)
            {
                Button clickedButton = (Button)sender;
                string letterPressed = clickedButton.Text.ToString();

                LoadContacts(letterPressed);
            }
        }

        private void LoadContacts(string letter)
        {
            
            listBox1.Items.Clear();

            string l = letter/*.ToUpper()*/;

            for (int i = 0; i < contactList.Count; i++)
            {
                string nickname = contactList.ElementAt(i).Split('|')[0];
                string firstLetter = nickname.Substring(0, 1).ToUpper();
                if (l == firstLetter)
                {
                    listBox1.Items.Add(nickname);
                }

            }
        }

        private void listBox1_selectIndexChange(object sender, EventArgs e)
        {
            string nickname = listBox1.SelectedItem.ToString();

            for (int i = 0; i < contactList.Count; i++)
            {
                string nn = contactList.ElementAt(i).Split('|')[0];
                string gender = contactList.ElementAt(i).Split('|')[1];
                if (nn == nickname)
                {
                    textBoxName.Text = contactList.ElementAt(i).Split('|')[2];
                    textBoxAddress.Text = contactList.ElementAt(i).Split('|')[3];
                    textBoxPhone.Text = contactList.ElementAt(i).Split('|')[4];
                    textBoxEmail.Text = contactList.ElementAt(i).Split('|')[5];
                    pictureBox1.Image = new Bitmap((Image)Version1.Properties.Resources.ResourceManager.GetObject(nickname));

                    if (gender == "female")
                    {
                        
                        textBoxName.ForeColor = Color.Pink;
                        textBoxAddress.ForeColor = Color.Pink;
                        textBoxEmail.ForeColor = Color.Pink;
                        textBoxPhone.ForeColor = Color.Pink;

                    }
                    else
                    {
                        textBoxName.ForeColor = Color.Blue;
                        textBoxAddress.ForeColor = Color.Blue;
                        textBoxEmail.ForeColor = Color.Blue;
                        textBoxPhone.ForeColor = Color.Blue;
                    }

                    break;
                }
            }
        }

        private void copyRightNotice_Click(object sender, EventArgs e)
        {
            AboutBox1 aboutBox = new AboutBox1();
            aboutBox.Show();
        }

        private void exit_click(object sender, EventArgs e)
        {
            this.Close();
        }
 
    }
}




I am just a newbie in this field, so please bear with me :( I really want to learn how to add this functionality. Thanks in advance, guys/

Is This A Good Question/Topic? 0
  • +

Replies To: Disabling and enabling buttons

#2 SurfingShark  Icon User is offline

  • D.I.C Head

Reputation: 38
  • View blog
  • Posts: 188
  • Joined: 18-April 11

Re: Disabling and enabling buttons

Posted 01 July 2011 - 02:01 PM

When you load whatever data into the text boxes, at the end of that method just set the property myButton.Enabled to true. Then in the portion of your code where you determine that this button should no longer be enabled, set it to false.
Was This Post Helpful? 1
  • +
  • -

#3 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5582
  • View blog
  • Posts: 11,941
  • Joined: 02-June 10

Re: Disabling and enabling buttons

Posted 01 July 2011 - 08:03 PM

It would help us, to help you, if you had actually asked a question.

"I need help to...." doesn't really tell us anything about where you are hung up or what you don't understand.

As shark said... Just the .Enabled property to true or false when you set/read/discover the appropriate condition.

Some examples:

myButton.Enabled = true;
myButton.Enabled = Nickname.StartsWith("A");
ButtonB.Enabled = !ButtonA.Enabled;


I hate to sound disheartening, but if you are this new to C# I think it would be in your interest to work through a book, lessons, tutorials etc. before trying to rush out and build a program from scratch with no experience.

A person does not say "I've never played an instrument nor can I read sheet music: I think I'll go write an opera as a self-teaching experience."


Standard resources, references and suggestions for new programmers.


I would recommend you start with "Hello World" just like the other million+ coders out there. Then work your way up to the more advanced tasks like this.

The problem with taking on large, complex tasks like this when you are new to coding is that
  • it will frustrate you to the point of quitting,
  • you don't know enough about coding to know where to start or in what direction to design your program
  • You risk learning via the 'Swiss cheese' method where you only learn certain bits and pieces for the one project but have huge holes in your education.


I am going to guess that you are trying to teach yourself C# without much guidance, a decent book or without knowing where to look. Sometimes just knowing where to look can make all the difference. Google is your friend.
Search with either "C#" or "MSDN" as the first word: "MSDN Picturebox", "C# Custom Events", "MSDN timer" etc.

But honestly, just typing away and seeing what pops up in Intellisense is going to make your self-education take 20 years. You can learn by trying to reverse engineer the language through banging on the keyboard experimentation - or you can learn by doing the tutorials and following a good "How to learn C#" book.

Free editions of Visual Studio 2010

May I suggest picking up a basic C# introductory book? There are so many great "How do I build my first application" tutorials on the web... There are dozens of "Learn C# in 21 days", "My first C# program" type books at your local book seller or even public library.

D.I.C. C# Resource page Start here
Intro to C# online tutorial then here...
C# control structures then here.
MSDN Beginner Developer video series
MSDN video on OOP principals, making classes, constructors, accessors and method overloading
MSDN Top guideline violations, know what to avoid before you do it.
Design patterns as diagrams

The tutorials below walk through making an application including inheritance, custom events and custom controls.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Passing values between forms/classes

Working with environmental variables
'Why do we use delegates?' thread

Debugging tutorial
Debugging tips
Debugging in detail
Great debugging tips
It still doesn't work, article

Build a Program Now! in Visual C# by Microsoft Press, ISBN 0-7356-2542-5
is a terrific book that has you build a Windows Forms application, a WPF app, a database application, your own web browser.

C# Cookbooks
Are a great place to get good code, broken down by need, written by coding professionals. You can use the code as-is, but take the time to actually study it. These professionals write in a certain style for a reason developed by years of experience and heartache.

Microsoft Visual Studio Tips, 251 ways to improve your productivity, Microsoft press, ISBN 0-7356-2640-5
Has many, many great, real-world tips that I use all the time.

Writing a text file is always one of the first things people want to do, in order to store data like high-scores, preferences and so on
Writing a text file tutorial.
Reading a text file tutorial.

And everyone always wants to connect to a database, right out of the gate so
Database tutorials right here on DIC

These are just good every-day references to put in your bookmarks.
MSDN C# Developers Center with tutorials
Welcome to Visual Studio

Have you seen the 500+ MSDN Code Samples? They spent a lot of time creating samples and demos. It seems a shame to not use them.

Let me also throw in a couple tips:
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.
  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.
    btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)
  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like Index, TimeOut, Row, Column and so on. You should avoid 'T' for the timer. Amongst other things 'T' is commonly used throughout C# for Type and this will lead to problems. There are naming guidelines you should follow so your code confirms to industry standards. It makes life much easier on everyone around you, including those of us here to help. If you start using the standards from the beginning you don't have to retrain yourself later.
  • Try to avoid having work actually take place in GUI control event handlers. It is usually better to have the GUI handler call other methods so those methods can be reused and make the code more readible.
    btnSave(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    SaveMenuItem(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    SaveContextMenu(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    Form1_Closing(object sender, eventargs e)
    {
        if (IsDirty) SavePreferences();
    }
    

Was This Post Helpful? 2
  • +
  • -

#4 zel2zel  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 19-September 09

Re: Disabling and enabling buttons

Posted 16 July 2011 - 11:51 PM

Okay, I'll study harder. Thank you for the tip :D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1