Is it possible to do conditional statements in the CssClass property? - c#

I'm using a repeater control. One of my item attributes is a boolean. I know I can do a conditional statement in the Text property, such as:
Text='<%# Item.Boolean ? "Text 1" : "Text 2" %>
However, what if I want the same text but a different CSS style depending on the boolean?
Is code like the following possible?
CssClass=<%# Item.Boolean ? "CssClass1" : "CssClass2" %>

You cannot do it like that. is not a runat server type of tag, so it cannot attempt to execute the logic there. Instead, you need to set the properties for the gridview in Page_PreRenderComplete.
Use something like the following to do it:
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
this.FormatGridviewRows();
}
private void FormatGridviewRows()
{
foreach (GridViewRow row in this.GridView1.Rows)
{
// Don't attempt changes on header / select / etc. Only Datarow
if (row.RowType != DataControlRowType.DataRow) continue;
// At least make sure everything has the default class
row.CssClass = "gridViewRow";
// Don't affect the first row
if (row.DataItemIndex <= 0) continue;
if (row.RowState == DataControlRowState.Normal || row.RowState == (DataControlRowState.Normal ^ DataControlRowState.Edit))
{
row.CssClass = !this.cbForceOverride.Checked
? "gridViewRow"
: "gridViewRow gridViewRowDisabled";
}
if (row.RowState == DataControlRowState.Alternate || row.RowState == (DataControlRowState.Alternate ^ DataControlRowState.Edit))
{
row.CssClass = !this.cbForceOverride.Checked
? "gridViewAltRow"
: "gridViewAltRow gridViewAltRowDisabled";
}
}
}
and then in your stylesheet:
.gridViewRow {
background-color: #f2f2f2;
}
.gridViewAltRow {
background-color: #ffffff;
}
.gridViewRow, .gridViewAltRow {
color: #000000;
}
.gridViewRowDisabled, .gridViewAltRowDisabled {
color: #DDDDDD;
}

Related

Change MudBlazor table background color by row item condition

I am trying to change the color of a row in a mudblazor table. The problem is, I can't add a functionality to change the color by the condition of the element of the row.
<MudTable Items="#context.orderPositions" Context="AddressContext" Hover="true" Breakpoint="Breakpoint.Sm" Elevation="0" Style="background-color: #(AddressContext.OrderPositionStatus == PositionStatus.rdy ? yellowgreen : blue;">
You can:
<MudTable Items="#Items" Hover="true" RowStyleFunc="RowStyleFunc">
And then
private string RowStyleFunc(Item arg1, int index)
{
switch (arg1.Title)
{
case string a when a.Contains("1/4"):
return "background-color:blue";
case string b when b.Contains("2/4"):
return "background-color:red";
default: return "background-color:white";
}
}
I wanted to be able to hide row items marked for deletion by default and then show them in red when when a toggle switch was enabled. So on my component I appended a switch:
<MudSwitch #bind-Checked="#blnShowDeleted" Color="Color.Warning">Show deleted</MudSwitch>
#Nadav Hury's answer told me about RowStyleFunc which led me to the MudBlazor documentation and RowClassFunc which I thought might be a better bet. So I changed the code for the table declaration:
<MudTable Items="objVmCustomers" RowClassFunc="ShowDeleted">
I created a ShowDeleted method in the code-behind razor.cs class:
public string ShowDeleted(VmCustomer objVmCustomer, int index)
{
if(objVmCustomer.dtDeleted != null)
{
if (blnShowDeleted == true)
{
return "show-deleted";
}
return "hide-deleted";
}
return "";
}
Then I created two CSS classes to suit the code above:
.show-deleted td { --mud-palette-text-primary: red; }
.hide-deleted { display: none; visibility: collapse; }
There is a gotcha here: you can't just go color:red; in the show-deleted declaration because the CSS variable --mud-palette-text-primary will override it. You have to override the CSS variable (I discovered this by inspecting the element).
By using a CSS class that operates on all the TD elements within a row, this gets over the 'dirtiness' that #T0bi complains of when using multiple style attributes.
It's not a complete answer, but in your code, style in <MudTable> will change all background color. You need to determine RenderFragment's color like, <MudTd Style="background-color:yellow;</MudTd>"
https://try.mudblazor.com/snippet/cYcFEMkdVtcQQNnQ
I have a solution but it feels kinda dirty...
<RowTemplate>
<MudTd DataLabel="Menge" Style="#(AddressContext.OrderPositionStatus == PositionStatus.rdy ? $"background:{Colors.BlueGrey.Darken4};" : $"background:{Colors.Cyan.Darken1};")">#AddressContext.orderItem.ItemQuantity</MudTd>
<MudTd DataLabel="Itemcode" Style="#(AddressContext.OrderPositionStatus == PositionStatus.rdy ? $"background:{Colors.BlueGrey.Darken4};" : $"background:{Colors.Cyan.Darken1};")">#AddressContext.orderItem.ItemCode</MudTd>
<MudTd DataLabel="Itemname" Style="#(AddressContext.OrderPositionStatus == PositionStatus.rdy ? $"background:{Colors.BlueGrey.Darken4};" : $"background:{Colors.Cyan.Darken1};")">#AddressContext.orderItem.ItemName</MudTd>
</RowTemplate>
As shown, it is possible to change the color within the row template. So the context is available. Its annoying work for each row/colum- combination but in the end it works.

Dynamic change of css class in the field

I would like to change the color in the (td) field [change color - change / transfer to a different css class?]
Condition:
The condition comes from the "if" query. if (sb == true) then nothing changes, if (sb == false) "[else]"
then the css class in (td class="InputsForUserColor1") may change to class="InputsForUserColor1Change".
Notes
(td class="InputsForUserColor2") is unchanged
My html code (razor/C#):
the variable "sb" is outside "if", assumes a different value
#for (int sth = 0; sth< ViewBag.sth; sth++)
{
if (sb == true)
{
varSth = "00:00";
}
else
{
varSth = "20:00";
}
#for (int sthElse = 0; sthElse< ViewBag.sthElse; sthElse++)
{
if (nr_columns == 2)
{
<td id="td01" class="InputsForUserColor1"></td>
}
if (nr_columns == 3)
{
<td id="td01" class="InputsForUserColor2"></td>
}
}
}
My CSS code:
.InputsForUserColor1, area {
background-color: papayawhip;
border: hidden;
align-content: center;
align-items: center;
vertical-align: central;
}
.InputsForUserColor1Change, area {
background-color: white;
border: hidden;
align-content: center;
align-items: center;
vertical-align: central;
}
personally I didn't write it because I don't know how to approach it
If the color should only be set once, while the page is rendered on the server:
set the target class in a variable of the CSHMTL page (Razor C# code block with #{}).
use the value of this variable (Razor #variableName Syntax).
#* assume that 'sb' does not change its value inside the for loop *#
#{ var userColor1 = sb == true ? "InputsForUserColor1" : "InputsForUserColor1Change"; }
#for (int sth = 0; sth< ViewBag.sth; sth++) {
#for (int sthElse = 0; sthElse< ViewBag.sthElse; sthElse++) {
if (nr_columns == 2) {
<td id="td01" class="#userColor1"></td>
}
else if (nr_columns == 3) {
<td id="td01" class="InputsForUserColor2"></td>
}
}
}
This will render the HTML with the correct class set when the page is delivered to the client browser.
This will not work if the color needs to change due to user interactions on the client (browser) side. In this case, you have to use a client script (JavaScript) to change the color dynamically. To do this, see jQuery addClass.

How to change the text color of disabled Asp.net DropDownList

I searched for some time on this question and couldn't find a working answer anywhere.
I have an asp DropDownList that gets disabled and enabled based on whether the form is in view mode or not. The problem I was having is when the DropDownList.Enabled = false the text is hard to read(grey on lightgrey).
I solved the issue by passing the DropDownList to some methods.
public void DisableDDL(ref DropDownList DDL)
{
DDL.BackColor = System.Drawing.Color.LightGray;
foreach (ListItem i in DDL.Items)
{
if (i != DDL.SelectedItem)
{
i.Enabled = false;
}
}
}
public void EnableDDL(ref DropDownList DDL)
{
DDL.BackColor = System.Drawing.Color.White;
foreach (ListItem i in DDL.Items)
{
i.Enabled = true;
}
}
Is there another way to do this?
I tried using css but that didn't work.
<style>
.disabledStyle
{
color: black;
}
</style>
myDDl.CssClass = "disabledStyle";
There is no readonly property for the dropdownlist control. But you can move the focus to another control when it receives the focus and that will prevent it from being changed and leave the text black.
You need to apply the style to each individual ListItem, and not to the DropDownList itself
I have just put in a dropdownlist and put it to enabled false in the controller, then I found out that it has a class called "aspNetDisabled", I have tried to use CSS to change color on it, it works perfectly.
<style>
.aspNetDisabled
{
color: #FFF;
background-color: #000;
}
</style>
In the code, if you put the dropdownlist, "ddl.enabled = false", it will be like this:
<select name="DropDownList1" id="DropDownList1" disabled="disabled" class="aspNetDisabled"></select>
If the dropdownlists are surrounded by a div with a class, use the class to define the disabled ones:
<style>
.MyCssClass[disabled]
{
color: #FFF;
background-color: #000;
}
</style>
Or try
:disabled,[disabled]
{
-ms-opacity: 0.5;
opacity:0.5;
}
</style>
As said in here:
http://forums.asp.net/t/2028164.aspx?IE+11+disabled+buttons+links+not+shown+as+greyed+out
The simplest way to do that:
<style>
[disabled] { /* Text and background colour, medium red on light yellow */
color:#933;
background-color:#ffc;
}
</style>

get checkbox Controls by custom attribute name in C#

I have a collection of checkbox some 40-50 nos and i have set a attribute 'attr-ID' for each checkbox which is a unique value ID in database. how can i get the control by attribute name in c# code. I want to check some of the checkbox according to dB values on page load event.
<input type="checkbox" id="rdCervical" attr-ID='111' runat='server' />
Is this what you want?
protected void Page_Load(object sender, EventArgs e)
{
var cb = FindControlByAttribute<HtmlInputCheckBox>(this.Page, "attr-ID", "111");
}
public T FindControlByAttribute<T>(Control ctl, string attributeName, string attributeValue) where T : HtmlControl
{
foreach (Control c in ctl.Controls)
{
if (c.GetType() == typeof(T) && ((T)c).Attributes[attributeName]==attributeValue)
{
return (T) c;
}
var cb= FindControlByAttribute<T>(c, attributeName, attributeValue);
if (cb != null)
return cb;
}
return null;
}
if (rdCervical.Attributes["attr-ID"] != null)
{
string id = rdCervical.Attributes["attr-ID"];
rdCervical.Checked = true;
}
I assume you are adding the checkboxes programatically. In that case, make a container <div id="checkContainer" runat="server"></div> and put all your checkboxes inside it. Then just use checkContainer.InnerHtml and parse that code with this library. You can then easily use the library API to find elements by attribute, I think the method was SelectNodes
Without this library, there is no easy way to navigate through HTML elements from code.

How I turn label in asp red

Hi I would like to turn label red in .aspx when user enters wrong answer into textbox.
but not know how, hw I can do this?
You can do this using javascript (call this code from onchange of the textbox):
<label for="myTextBox" id="myLabel">For my textbox</label>
<input id="myTextBox" onchange="ValidateAnswer();">
function ValidateAnswer() {
var txtBox = document.getElementById('myTextBox');
if(txtBox.value != "answer") {
document.getElementById('myLabel').style.color = 'red';
}
}
You can also use the Validator controls if you're using ASP.Net:
<asp:CustomValidator runat="server" ID="cvAnswer"
ControlToValidate="myTextBox"
ErrorMessage="required"
ClientValidationFunction="ValidateAnswer"
ValidateEmptyText="true"
Display="Dynamic"
ValidationGroup="First"
ForeColor="red" >
</asp:CustomValidator>
function ValidateAnswer(sender, args) {
args.IsValid = args.Value != "" && args.Value == "answer here";
if(!args.IsValid) {
document.getElementById('myLabel').style.color = 'red';
}
return;
}
From the server side code:
if(this.txtBox.Text.Length == 0)
{
//no value entered
lblMyLabel.BackColor = Color.Red;
lblMyLabel.Text = "Invalid entry";
}
Client side you can do this:
Markup:
<asp:TextBox onchange="Validate();" runat="server" id="myTextBox"/>
JS:
function Validate()
{
var t = document.getElementByID("myTextBox");
var l = document.getElementByID("myLabel");
if (t.Length == 0)
{
l.style.backgroundColor='red';
}
}
There are multiple options, some server side, and some client side, but in both cases it involves validation. Essentially you are looking to change a css class or other style property on the label.
C# code behind:
if(yourConditionText != "YourExpectedValue")
{
youTextBox.BackColor = System.Drawing.Color.Red;
}
In the Server side button click event (which will be automatically generated when you double click on the button in Design view of the aspx page):
protected void Button_Click(...)
{
if(txtYourTextBox.Text != "YourDesiredValue")
{
lblYourLabel.ForeColor = Color.Red;
}
}
Better still, you could use String.Compare (recommended) as below:
if(string.Compare(txtYourTextBox.Text, "YourDesiredValue") != 0) //0 = Match
{
lblYourLabel.ForeColor = Color.Red; //For backColor set BackColor property
}
Hope it helps!

Categories