简体   繁体   中英

changing CSS class for object sender control

i'm making a workbook creator in C#.net ( using visual studio )

the book is build from the text part and the question part.

all the answers for the question are inside the text and the user need to click on the right answer. if he's right then the word become green and if he's wrong it become red.

i'm creating the clickeable text with LINKBUTTON, i gave the link button CssStyle class and after the user clicking the word i want to change the class for this link to a different class.

this is the code i using for creating the linksbutton:

  public void createQusetion(Panel lefttext, Panel question, string text, string          
   questionText, string answer)
{

    string[] Qbuttonstext = text.Split(' ');
    _numberWords = Qbuttonstext.Length;
    for (int i = 0; i < _numberWords; i++)
    {
        LinkButton answerButton = new LinkButton();
        if (Qbuttonstext[i] == answer)
        {
            answerButton.ID = "answer" + i;

        }
        else
        {
            answerButton.ID = "word" + i.ToString();
        }
        answerButton.Text = Qbuttonstext[i].ToString() + " ";
        answerButton.CssClass = "textbuttonB4";

        answerButton.Click += new EventHandler(checkAnswer);

        lefttext.Controls.Add(answerButton);
    }


}

and for the checking the question:

 private void checkAnswer(object sender, System.EventArgs e)
{
    for (int i = 0; i < _numberWords; i++)
    {
        if (((Control)sender).ID.ToString() != null)
        {
            if (((Control)sender).ID.ToString() == "answer" + i.ToString())
            {
                ((Control)sender).CssClass = "textbuttonRight";

            }
            else
            {
                ((Control)sender).CssClass = "textbuttonwrong";

            }
        }
    }
}

the VS2010 giving me misatake for the : ((Control)sender).CssClass .

what is the right way?

You can do a type-independent control this way. It will run for all controls have Id and CssClass Properties.

    private void checkAnswer(object sender, System.EventArgs e)
    {
        var cssClass = sender.GetType().GetProperty("CssClass");
        var id = sender.GetType().GetProperty("ID").GetValue(sender, null);
        for (int i = 0; i < _numberWords; i++)
        {
            if (id!=null)
            {
                if (id.ToString() == "answer" + i.ToString())
                {
                    cssClass.SetValue(sender, "textbuttonRight", null);
                }
                else
                {
                    cssClass.SetValue(sender, "textbuttonRight", null);
                }
            }
        }
    }

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