I have a dynamically created checkbox from code behind that has a long label on my webform asp.net project. When the text wraps to a new line the new line of text starts directly under the checkbox itself. How can I dynamically set the checkbox so the new line is automatically indented if needed. Not all dynamically created checkboxes have a long label.
Here is my code that creates the checkbox:
MyObject obj = SetNewObject("Supervisor");
CheckBox objCheck6 = new CheckBox();
objCheck6.ID = obj.GetFieldValue("Name");
objCheck6.Text = GetControlTitle("Supervisor");
objCheck6.Checked = obj.GetFieldValue("Value").ToLower() == "true";
tableCell1.Controls.Add(objCheck6);
I have tried a couple things that have not worked. I tried the following, one at a time and each seemed to have zero effect on the checkbox or checkbox's text at all:
objCheck6.Style.Add("margin-left", "20px");
objCheck6.LabelAttributes.Add("margin-left", "20px");
objCheck6.TextAlign = TextAlign.Right;
objCheck6.TextAlign = TextAlign.Left;
A point in the right direction would be much appreciated. Thanks!
Edit your css and add this so all the labels from the checkBoxes are affected.
label{
display: block;
margin-top: -18px;
margin-left: 20px;
}
If this causes a problem because you have other labels in your page, name that css class and add it dynamically to your checkBox like this:
objCheck6.InputAttributes["class"] = "className";
UPDATE
This can also be achieved with the code mentioned in the comments:
objCheck6.LabelAttributes.Add("style", "display:block;margin-top:-18px;margin-left:20px;");
I used this question as a reference.
Related
I want a textbox on my Web Part that will grow vertically on demand. That is, it will be one line unless the user enters too much text for that line, at which point it word wraps and grows vertically to accommodate the verbosity of the user.
I am creating my controls/elements dynamically, and I create this element like so:
boxPaymentExplanation = new TextBox()
{
CssClass = "dplatypus-webform-field-input"
};
boxPaymentExplanation.Width = 660;
boxPaymentExplanation.Style.Add("display", "inline-block");
I tried adding this line, in the hopes of achieving this functionality:
boxPaymentExplanation.Style.Add("TextMode", "MultiLine");
...but it makes no apparent change to the textbox's behavior - I can enter text into it "until the bovines come back to the barn" but it simply keeps adding the characters to the end of the textbox on a single row. It never wraps, so it never grows.
UPDATE
This is the jQuery that works (derived from the link that Christopher Jennings provided):
$(document).on("keyup", "[id$=explainPaymentTextBox]", function (e) {
while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
$(this).height($(this).height() + 1);
};
});
...along with this C#:
boxPaymentExplanation = new TextBox()
{
CssClass = "dplatypus-webform-field-input",
ID = "explainPaymentTextBox"
};
boxPaymentExplanation.Width = 660;
boxPaymentExplanation.Style.Add("display", "inline-block");
boxPaymentExplanation.TextMode = TextBoxMode.MultiLine;
UPDATE 2
Unfortunately, although the descent-into-the-mælström-esque jQuery above works for dynamically growing the textbox, it doesn't work if the user removes text; I would like it also to shrink when that happens...
You're on the right track. You need to set the TextMode property to Multiline. However, the approach you took is to add an HTML tag attribute rather than set the .NET property. Simply replace boxPaymentExplanation.Style.Add("TextMode", "MultiLine"); with boxPaymentExplanation.TextMode = TextBoxMode.MultiLine;
I am trying to create a large number of checkboxes and felt it would not be efficient if I created them in the xaml.
Is it possible to dynamically create checkboxes and specify the group box/grid and its location in C# only? I know we can dynamically create the check boxes but I am not too sure how to manage its location via c#.
I am relatively new to WPF, thanks!
#user2584960 "Once I created them, how can I reference them? I am stuck... I gave the checkbox a name before adding to children but cannot reference them... "
I can only imaging you're trying to do:
Checkbox c = panel.Children.Add(new Checkbox());
You're not returning anything when you add to the panel, so you cant "Reference" a checkbox class.
As #Alex G was saying, his answer is showing how you add to the content window if you need to set a refrence just create a new class then add it to the window:
StackPanel panel = new StackPanel();
this.Content = panel;
CheckBox c = new CheckBox();
c.IsChecked = true;
//you Could create a loop to loop all of the list checkboxes to add them.
panel.Children.Add(c);
most likely you have a Page that has Content property
you should be able to do following
StackPanel panel = new StackPanel();
this.Content = panel;
panel.Children.Add(new CheckBox());
panel.Children.Add(new CheckBox());
panel.Children.Add(new CheckBox());
I guess you can reference them as following
CheckBox cb = new CheckBox();
panel.Children.Add(cb);
I have a table which I create programatically in my code behind file and set the colours of alternate row to gray for easier visibility like so:
<New cells and rows created here>
tblResults.GridLines = GridLines.Both;
tblResults.BorderStyle = BorderStyle.Solid;
tblResults.HorizontalAlign = HorizontalAlign.Center;
if (rowNumber % 2 == 1)
{
tblRow.BackColor = System.Drawing.Color.LightGray;
}
tblResults.Rows.Add(tblRow);
tblResults.CssClass = "myclass" ;
pnlContent.Controls.Add(tblResults);
I also want to have the rows highlighted when a user hovers over them like so:
.myclass tr:hover
{
background: #FCF;
}
Now the hover only seems to work for the rows which are not highlighted gray from the c# code which I assumes takes precedence over the css.
How can I also make those gray rows work with the css hover?
Try this hope it helps, I think some where the Style inside the page is overwriting your light Grey Background. Try this it will be ease to find the solution
if (rowNumber % 2 == 1)
{
tblRow.Attributes.Add("Class","ClassName_grey");
}
else{
tblRow.Attributes.Add("Class","ClassName_nothing")
}
.myclass tr:hover
{
background: #FCF;
}
.ClassName_grey {
background: #eeeeee;
}
You might try
.myclass tr:hover
{
background-color: #FCF;
}
Or adding the !important qualifier. The former is basically setting the same style as the server-side code should be, whereas your code was setting the less specific background (all aspects of it, not just colour).
Otherwise try viewing the source or using developer tools to see what style attribute you need to overwrite.
I am working on a solution in C# and ASP.NET 4.0 I am trying to get the value of a radiobutton from my page that was dynamically created based on some database information.
Here is what gets generated in the page source:
<td>
<input id="masterMain_3Answer_0" type="radio" name="ctl00$masterMain$3Answer"
value="Y" onclick="return answeredyes(3);" />
<label for="masterMain_3Answer_0">Y</label>
</td>
<td>
<input id="masterMain_3Answer_1" type="radio" name="ctl00$masterMain$3Answer"
value="N" onclick="return answeredno(3,'desc');" />
<label for="masterMain_3Answer_1">N</label>
</td>
Inside the OnClick function of my submit button I want to gather wether Y or N has been selected based on the user's input.
Here is what I have written so far:
RadioButton _rbAnswer = new RadioButton();
RadioButtonList _rbList = new RadioButtonList();
ContentPlaceHolder cp = (ContentPlaceHolder)Master.FindControl("masterMain");
_rbAnswer = (RadioButton)Master.FindControl("masterMain_3Answer_0");
HtmlInputRadioButton rb = (HtmlInputRadioButton)Master.FindControl("masterMain_3Answer_0");
_rbAnswer = (RadioButton)cp.FindControl("masterMain_3Answer_0");
_rbList = (RadioButtonList)cp.FindControl("masterMain_3Answer_0");
I am able to get the ContentPlaceHolder without any issues but the rest of the objects are null after it attempts to get the . I have also attempted removing the "masterMain_" but still doesn't want to find the controls.
Here is the code in which the individual radiobuttonlists are added
TableRow _tempRow = new TableRow();
TableCell _cellOK = new TableCell();
RadioButtonList _rbList = new RadioButtonList();
_rbList.ID = r[0].ToString()+"Answer";
_rbList.RepeatDirection = RepeatDirection.Horizontal;
//add options for yes or no
ListItem _liOk = new ListItem();
_liOk.Value = "Y";
ListItem _linotOk = new ListItem();
_linotOk.Value = "N";
_rbList.Items.Add(_linotOk);
//add cell to row
_rbList.Items.Add(_liOk);
_cellOK.Controls.Add(_rbList);
_tempRow.Cells.Add(_cellOK);
//add the row to the table
stdtable.Rows.Add(_tempRow);
To be able to quickly find dynamically created controls, add a dictionary to your page class:
private Dictionary<string, Control> fDynamicControls = new Dictionary<string, Control>();
then when a new control is created in code and its ID is assigned:
fDynamicControls.Add(newControl.ID, newControl);
and when you need control's reference:
Control c = fDynamicControls["controlIdThatYouKnow"];
When using FindControl don't use the id that's generated by the page. Use the ID that you specified inthe aspx.
If this is inside a Repeateror another DataBound control, you have to first find the current record. (GridViewRow or RepeaterItem) first, an use that item's .FindControl function.
See this (different - not duplicate) question to see a code example of how to do it: How to find control with in repeater on button click event and repeater is placed with in gridview in asp.net C#
When you create dynamic controller give specific ids for them. This facilitate to generate controls with our own id. therefore then we can access the controls with this id.
And also use OnInit life cycle event to generate dynamic controllers, this is the best place to generate them.
RadioButton _rbAnswer = new RadioButton();
_rbAnswer.ID="ranswerid";
Given your update, you'll find that your control heirarchy is fairly deep. You have a RadioButtonList inside a cell inside a row inside a table ...
FindControl is a method that needs to be called on a specific object and can only find objects that are actual children of that object. In this case, you either need to build a recursive method or go directly to the control in question. Since so many of these controls are generated dynamically, you'll have no real way of accessing them directly so building the recursive function may be simplest. However, on very large pages this method can be very resource consuming:
public static WebUserControl FindControlRecursive(this WebUserControl source, string name)
{
if (source.ID.Equals(name, StringComparison.Ordinal))
return source;
if (!source.Controls.Any()) return null;
if (source.Controls.Any(x => x.ID.Equals(name, StringComparison.Ordinal))
return source.FindControl(name);
WebUserControl result = null;
// If it falls through to this point then it
// didn't find it at the current level
foreach(WebUserControl ctrl in source.Controls)
{
result = ctrl.FindControlRecursive(name);
if (result != null)
return result;
}
// If it falls through to this point it didn't find it
return null;
}
This is an extension method that would allow you to call this on your ContentPlaceHolder control:
var _cp = (ContentPlaceHolder)Master.FindControl("masterMain");
RadioButtonList _rbList = _cp.FindControlRecursive("3Answer");
if (_rbList != null)
// ... Found it
Note: Treat the above as psuedo-code. It has not be implemented by me anywhere so may (likely) require tweaking to behave exactly right.
I have some link buttons in which I am dynamically adding a style to it. I am doing the following in a method:
LinkButton lb = new LinkButton();
lb.Style["font-weight"] = "bold";
When the another link is clicked, it should unbold the link button that is bold and bold the currently clicked one, so in the method that is doing this, I have tried:
lb.Style["font-weight"] = "none";
The above does not work though, the previously selected link stays bold.
I just realized the possible problem. I am creating multiple links and what it looks like is that since all the links are named lb, it never removes the bold. I am trying to think of a way for it to remember the previously selected link and to only unbold that one.
Can I suggest an alternative approach?
Set a CSS Style:
.selected { font-style: bold; }
When a link is clicked set that link's CSS class to "selected" and the others to "";
EDIT: To accommodate for existing Css Class
const string MY_CLASS = "links";
lb1.CssClass = MY_CLASS + " selected"; // selected
lb.CssClass = MY_CLASS; // not selected
You can quickly get into trouble when defining inline styles, in that they're difficult to overwrite.
EDIT 2:
Something like this code should work. You may have to loop through all the LinkButtons in the list, but I don't think so. I'd just turn off ViewState on the LinkButtons.
// container for links. so you can reference them
// outside of the creation method if you wish. I'd probably call this method in the
// Page_Init Event.
List<LinkButton> listOfLinks = new List<LinkButton>();
const string MY_LB_CLASS = "linkButton"; // generic lb class
private void createSomeLinks() {
for (int i = 0; i < 10; i++) {
// create 10 links.
LinkButton lb = new LinkButton()
{
ID = "lb" + i,
CssClass = MY_LB_CLASS
};
lb.Click += new EventHandler(lb_Click); // Add the click event
}
// You can bind the List of LinkButtons here, or do something with them.
}
void lb_Click(Object sender, EventArgs e) {
LinkButton lb = sender as LinkButton; // cast the sender as LinkButton
if (lb != null) {
// Make the link you clicked selected.
lb.CssClass = MY_LB_CLASS + " selected";
}
}
Try lb.Style.Remove("font-weight"). I didn't test it, but you can try it out.
Alternatively, have you tried settings the Font.Bold property?
lb.Font.Bold = true;
Try ListBox1.Attributes.Add("style","font-weight:bold");
and ListBox1.Attributes.Add("style","font-weight:normal");
or even better is
// css
.active {font-weight:bold}
.notactive {font-weight:normal}
//c#
ListBox1.CssClass = "active";
ListBox1.CssClass = "notactive ";
you could try lb.Style.Remove("font-weight");
set the font bold in the click event of the link button and set the enable view state property to false in the click event itself which will reset the link to the normal foam in the other click