views:

277

answers:

3

So, I'm trying to dynamically add a button to a site to give the user of an idea of what they are adding to a form. However, when it renders a new button, it keeps providing the value property as "" and ignoring the attribute that I add. I've attempted to fix this to no avail, including removing the value attribute before adding in my version and clearing ALL the attributes.

WebControl myControl = null;
string[] elementInfo = elementCode.Split(new char[] { ';' });
        switch (elementID)
        {
            case 1:
                myControl = new Button();
                myControl.Attributes.Remove("value");
                myControl.Attributes.Add("type","submit");
                break;
            case 2:
                myControl = new TextBox();
                myControl.Attributes.Clear();
                myControl.Attributes.Add("type", "text");
                break;
            case 3:
                myControl = new CheckBox();
                myControl.Attributes.Clear();
                myControl.Attributes.Add("type", "checkbox");
                break;
        }
        if (myControl != null)
        {
            string[] properties;
            if (elementCode.Length > 0)
            {
                foreach (string attr in elementInfo)
                {
                    properties = attr.Split(new char[] { '=' });

                    myControl.Attributes.Add(properties[0], properties[1]);
                }
            }
            return myControl;
        }
        else
            return null;

I know that the loop is firing and the value returned in line 2 is a single line, "value=submit". In fact the markup comes out thus:

<div id="divLastElement">
    <input type="submit" name="ctl03" value="" type="submit" value="Submit Me!" />
</div>

I'm sure it's the first [value=''] that is causing it to be empty, but how do I override this behavior? (You can see that in the switch statement that generates the button I've tried to remove the value key early)

+2  A: 
Wim Hollebrandse
I don't seem to have access to the .Text property of the button when I check the intellisense. One thing that does work is choosing a textbox; then whatever is typed appears in the textbox as a default.
C Bauer
I missed out the cast to Button again. Standard base control WebControl does not have a Text property. See my edited snippet.
Wim Hollebrandse
Aaah, thanks! Wouldn't have thought to get around it that way myself!
C Bauer
+1  A: 

Try using a HtmlInputButton instead.

Phaedrus
A: 

YOu need to use the Text property. As you said in a comment you don't see the "Text" property in Intellisense. This is because to Intellisense, myControl is a WebControl (that you happen to make a Button). The WebControl is a base class for the specific controls you create, but itself does not have a "Text" property. Use the following instead:

myControl = new Button();
((Button)myControl).Text = "submit";
Colin