简体   繁体   中英

Change text of button when button is clicked c#

First time messing around with c# and I am trying to change the value of a button when the user clicks it.

The database has four names in it, when the code executes it only shows the name that is in the last row. I would like it to start with the first name, and then each time the button is pressed it should show another name until it has gone through all the names in the DB.

dataReader = command.ExecuteReader();

while (dataReader.Read())
{
    bText = dataReader.GetValue(1).ToString();
    button1.Text = bText;
}

The while loop does not work the way you think it does. What it does is looping over every result and set the button text. It does not pause anywhere (because there is nothing that tells the loop it should). So it simply iterates over every element as fast as it can. This explains why you only see the last result.

What you can do is to store a counter somewhere that you increment every time the button is pressed and only use the n-th element. Either by skipping the first few entries or depending on the database you use, you could only fetch a specific result entry (in MySQL this would be LIMIT and OFFSET in the select query)

For your specific problem (only 4 entries) I would fetch all entries at the start of the application and store them in an array. Then use the entry at the current index (=your counter) to set the text of the button.

You can try this. I've table named Colors having two columns: ID and Name.

public partial class FrmColor : Form
{
    SqlConnection con = new SqlConnection(@"<YOUR CONNECTION STRING HERE>");
    int pointer = 1;
    int rows = 0;

    public FrmColor()
    {
        InitializeComponent();
    }

    private void btnColor_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("Select Name from Colors Where ID = @ID", con);
        cmd.Parameters.AddWithValue("@ID", pointer);

        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        rdr.Read();
        string colorname = rdr.GetValue(0).ToString();
        con.Close();

        btnColor.Text = colorname;

        if (pointer == rows)
        {
            pointer = 1;
        }
        else
        {
            pointer++;
        }
    }

    private void FrmColor_Load(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("Select count(Name) From Colors", con);
        con.Open();
        rows = (Int32)cmd.ExecuteScalar();
        con.Close();
    }
}

Don't forget to add using System.Data.SqlClient;

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM