how to read value of style[“display”] property of webcontrol - c#

I have
<asp:RequiredFieldValidator ID="RequiredFieldValidatorFrom" runat="server" CssClass="ErrorLabel" ControlToValidate="FromDateTextBox" Display="Dynamic" ErrorMessage="<%$ Resources:GlobalResources, StartDateRequired %>">
</asp:RequiredFieldValidator>
and the css
.ErrorLabel
{
margin-left: 5px;
font-family: Segoe UI, Verdana;
font-size: 10px;
font-weight:lighter;
color: red;
vertical-align: top;
text-align: left;
display: block;
}
if my FromDateTextBox is empty I get the error message.
I want to check in my C# code whether my error is published on my page or not.
when I check the elementit from element inspection in chromewhen I don't have the error it's like this:
<span id="ctl00_PageMainContent_RequiredFieldValidatorFrom" class="ErrorLabel" style="color: red; display: none;">Start date required</span>
and when I have it it's like:
<span id="ctl00_PageMainContent_RequiredFieldValidatorFrom" class="ErrorLabel" style="color: red; display: inline;">Start date required</span>
just the display changes.
but how can I check this change in my c# code? I want to enable/disable a button based on this
Thanks in advance

You can achieve this by adding validation group
1) Add validationgroup property to the controls like below in your .aspx page
ValidationGroup="FormSubmit"
2) Use the below method to find whether that group is valid or not
protected bool IsGroupValid(String sValidationGroup)
{
foreach (BaseValidator validator in Page.Validators)
{
if (validator.ValidationGroup == sValidationGroup)
{
bool fValid = validator.IsValid;
if (fValid)
{
validator.Validate();
fValid = validator.IsValid;
validator.IsValid = true;
}
if (!fValid)
return false;
}
}
return true;
}
3) And finally call the above method in your code behind by passing the group name to check whether that group is valid or not.

Related

Change CssClass of an Textbox programatically

I've got a little Problem with my first ASP-Project.
Im offering the user and input-mask to enter data. At some points I want to control if the input is numeric. If not I want to change the border color of my Textbox.
This is my Textbox:
<asp:TextBox ID="tbOnlyNumeric" runat="server" Height="30px" CssClass="MyNumericBox" autocomplete="off"></asp:TextBox>
The style of the box looks like that:
.MyNumericBox
{
width:250px;
overflow: auto;
font-size: 20px;
position:relative;
right:111px;
border-color: #dcdcdc;
padding: 4px;
margin:15px;
border-width: 2px;
border-radius: 10px;
border-style: solid;
transition: box-shadow 0.3s, border 0.3s;
text-align: right;
padding-right: 18px;
outline: none;
}
My idea was to cast the the Text of the textbox in an try-catch-statment:
try
{
if (string.IsNullOrWhiteSpace(tbOnlyNumeric.Text))
{
throw new Exception();
}
else
{
salesExpected = Convert.ToInt32(tbOnlyNumeric.Text.ToString().Replace(".", string.Empty));
}
}
catch (Exception ex)
{
debugLabel.Text = "EX";
correct = false;
tbOnlyNumeric.CssClass = tbSalesExpected.CssClass.Replace("MyExpectedBox", "MyExpectedBoxWrong");
}
So if there is something wrong with my textbox it should look like that:
but instead it looks like that:
I already noticed that if watch it in chrome the old css class is deleted but the new one isn't addet.
Any idea why?
Thanks in advance
could you try this code. put this in your catch statement
ScriptManager.RegisterClientStartUpScript(this,this.GetType(),"pop","changeCssStyle();",true);
//in the head section of your aspx file create a script that will change the
//css style of the textbox
<script type="text/javascript">
function changeCssStyle(){
//if you are using a master page refer the id of textbox to the id of
//head content in master page e.g. MainContent_tbOnlyNumeric
//lets assume you already have reference to jquery in your head section
$('#MainContent_tbOnlyNumeric').css("border-color","red");
}
</script>
Finally figured outthat using:
tbSalesExpected.CssClass = "MyExpectedBoxWrong";
instead of:
tbOnlyNumeric.CssClass = tbSalesExpected.CssClass.Replace("MyExpectedBox", "MyExpectedBoxWrong");
fixes the problem.
Thanks for your answers and comments!

I want to get the ID of label using C# which is being created by jQuery on RunTime

First I will explain my scenario.
I have asp.net menu (dynamically created menu) and now I want to place push notification just like Facebook on my each menu option. I have designed it using CSS and put a label using jQuery.
if (res == "MenuIcons") {
$(this.parentElement).addClass('Notification');
var $label = $("<label ID=\"notificationlbl" + i + "\" style=\"position: absolute; margin-top: 2%; margin-left: -3.1%; margin-right:-3.3%; z-index: 99; color: white; font-size: 9px; font-family: Verdana; letter-spacing: -1px;\">").text('99');
$(this.parentElement.parentElement).append($label);
i++;
}
But I am totally confused that how to handle it using C# because I am unable to get the ID of the label created on run-time.
If you didn't understand please let me know and I will explain it more.
why don't you set a data attribute to each label, something like
var $label = $("<label data-element-type='notification' ID=\"notificationlbl" + i + "\" style=\"position: absolute; margin-top: 2%; margin-left: -3.1%; margin-right:-3.3%; z-index: 99; color: white; font-size: 9px; font-family: Verdana; letter-spacing: -1px;\">").text('99');
and then you can retrieve the whole collection with jQuery:
$("[data-element-type='notification']").each(function(){...});
Try adding runat="server" attribute in your label tag. You label tag id won't be available until runtime. So what you can do is search for the controllers by the id of your label. In code behind you can do as following
foreach(Contol c in this.Controls)
{
if(c.ID.contains("notificationlbl")
{
//your code
}
}

How can i use radiobuttonlist to show the table from database?

On selection of the radiobutton list I would like to query the database for the total and balances. In my database named eleave , I have 3 tables Annual , Special , Maternity.
Inside the table, I have total and balance columns for each type of leave.
<asp:RadioButtonList ID="rblleavetype" runat="server" CellPadding="0"
CellSpacing="0" style="text-align: left"
onselectedindexchanged="rblleavetype_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="al">Annualleave</asp:ListItem>
<asp:ListItem Value="ml">Maternity leave</asp:ListItem>
<asp:ListItem Value="sp">Special</asp:ListItem>
</asp:RadioButtonList>
This is the table codes for display the output.
<table cellpadding="5" cellspacing="0"
style="border: 1px solid #000000; width: 400px">
<tr>
<td style="border-right: 1px solid #000000; background-color: #D39A05; height: 25px; width: 200px; text-align: center; vertical-align: top;">
Total days for this leave type</td>
<td
style="border-left: 1px solid #000000; text-align: center;
background-color: #D39A05; height: 25px; width: 200px; vertical-align: top;">
Balance days available for this leave type</td>
</tr>
<tr>
<td style="border-right: 1px solid #000000; text-align: center; width: 200px; vertical-align: top;">
<asp:Label ID="ltotalleavetype" runat="server" CssClass="label"></asp:Label>
days</td>
<td style="border-left: 1px solid #000000; text-align: center; vertical-align: top; width: 200px;">
<asp:Label ID="lbalanceleavetype" runat="server" CssClass="label"></asp:Label>
days</td>
</tr>
</table>
I have been working on this system for months now and I still cant find the solution. p.s. I am still new in C# world.
It seems that you are new to web development using ASP.Net (or maybe you are being lazy. Just kidding :-D). Anyway, hope this will help you and someone in future.
First of all you need to have AutoPostBack="true" in your RadioButtonList. Then only it'll send a postback to the server and call the rblleavetype_SelectedIndexChanged event.
Ok, I created a working sample (Code is self explanatory and I've added comments where necessary). I'll explain the steps to display your data in a html table based on the radio button selection.
STEPS
Create a web page (I'm calling it LeaveBalance.aspx) with a RabioButtonList and the table (as you've already done).
<form id="frmLeaves" runat="server">
<div>
<asp:RadioButtonList ID="rblleavetype" runat="server" CellPadding="0" CellSpacing="0" style="text-align: left"
onselectedindexchanged="rblleavetype_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Selected="True" Value="al">Annual leave</asp:ListItem>
<asp:ListItem Value="ml">Maternity leave</asp:ListItem>
<asp:ListItem Value="sp">Special</asp:ListItem>
</asp:RadioButtonList>
<table cellpadding="5" cellspacing="0" style="border: 1px solid #000000; width: 400px">
<tr>
<td style="border-right: 1px solid #000000; background-color: #D39A05; height: 25px; width: 200px; text-align: center; vertical-align: top;">
Total days for this leave type</td>
<td
style="border-left: 1px solid #000000; text-align: center;
background-color: #D39A05; height: 25px; width: 200px; vertical-align: top;">
Balance days available for this leave type</td>
</tr>
<tr>
<td style="border-right: 1px solid #000000; text-align: center; width: 200px; vertical-align: top;">
<asp:Label ID="ltotalleavetype" runat="server" CssClass="label"></asp:Label>
days</td>
<td style="border-left: 1px solid #000000; text-align: center; vertical-align: top; width: 200px;">
<asp:Label ID="lbalanceleavetype" runat="server" CssClass="label"></asp:Label>
days</td>
</tr>
</table>
</div>
</form>
Then in your code behind file (LeaveBalance.aspx.cs) you should define your rblleavetype_SelectedIndexChanged method and some logic to load initial values at Page_Load event.
using System;
using MyLeave;
public partial class LeaveBalance : System.Web.UI.Page
{
// This is your UI logic.
/// <summary>
/// Create a private variable to hold all your leave retrieved from the database
/// I assume you have you'll have one row for each leave type
/// </summary>
public LeaveCollection AllLeaves {
get
{
if (ViewState["AllLeaves"] != null)
{
return (LeaveCollection)ViewState["AllLeaves"];
}
return new LeaveCollection();
}
set
{
// You need to save the collection in ViewState to persist the data
// Otherwise you'll loose all values AllLeaves will be reset in every postback
ViewState["AllLeaves"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetAllLeavesFromDatabase();
}
// I assume that annual leave radio option will be selected initially when the page loads
LoadDisplayTable(LeaveType.AL);
}
protected void rblleavetype_SelectedIndexChanged(object sender, EventArgs e)
{
LeaveType type = LeaveType.AL;
switch (rblleavetype.SelectedValue)
{
case "ml":
type = LeaveType.ML;
break;
case "sp":
type = LeaveType.SP;
break;
}
LoadDisplayTable(type);
}
/// <summary>
/// Gets all leaves from database.
/// </summary>
private void GetAllLeavesFromDatabase()
{
AllLeaves = new LeaveCollection();
/* At this point you should know how to retrieve your leave data from DB and fill the AllLeaves collection
E.g.
AllLeaves = DalService.GetAllLeavesFromDatabase(); // DalService could be your Data Access layer and GetAllLeavesFromDatabase() is one of it's methods
I'll be creating some dummy logic to fill the collection for demo purpose from this point onwards
*/
// Add annual leave to the collection
Leave al = new Leave(LeaveType.AL);
al.TotalDays = 15;
al.Available = 10;
AllLeaves.Add(al);
// Add Maternity leave
Leave ml = new Leave(LeaveType.ML);
ml.TotalDays = 60;
ml.Available = 5;
AllLeaves.Add(ml);
// Add Special leave
Leave sl = new Leave(LeaveType.SP);
sl.TotalDays = 5;
sl.Available = 3;
AllLeaves.Add(sl);
}
private void LoadDisplayTable(LeaveType type)
{
Leave selectedLeave = new Leave(type);
if (AllLeaves != null && AllLeaves.Count > 0)
{
// Here we find the leave object in the collection based on the leave type
selectedLeave = AllLeaves.Find(a => a.LeaveType == type);
}
// Populate your labels with selected leave type
ltotalleavetype.Text = selectedLeave.TotalDays.ToString();
lbalanceleavetype.Text = selectedLeave.Available.ToString();
}
}
The Leave class is created to hold the leave data (Leave.cs)
using System;
using System.Collections.Generic;
namespace MyLeave
{
// This is your modal. It defines how you'd hold your leave data in memory
// This collection will hold all your leaves
[Serializable]
public class LeaveCollection : List<Leave> { }
// Base class to create your leave
[Serializable] // Since you are saving the object in ViewState you need to mark this class as Serializable
public class Leave
{
public LeaveType LeaveType { get; set; }
public int TotalDays { get; set; }
public int Available { get; set; }
public Leave(LeaveType type)
{
this.LeaveType = type;
this.TotalDays = 0;
this.Available = 0;
}
}
// This Enum will hold the leave type
public enum LeaveType
{
AL = 1,
ML = 2,
SP = 3
}
}

CSS table properties

I am trying to set some styles for objects that are within a table but the problem is that the properties are not being applied to the actual objects.
the .tblData works fine but the label and textbox properties are supposed to be or any ASP.net label or textbox that appears within the table but the CSS doesnt get applied to them.
.tblData {
border: solid;
border-width: 1px;
height: 200px;
color: rgb(45,40,128);
background-color: white;
width: 100%;
border-radius:3px;
margin-top:3px;
}
/*Class for the labels*/
.tblData label {
width: 13%;
color:black;
border-radius:3px;
font-family:verdana;
border-radius:3px;
border-color:rgba(45,40,128,0.75);
border-width:1px;
}
/*Class for the data textboxes*/
.tblData textbox {
border-color: rgba(45,40,128,0.75);
border-width: 1px;
background-color:rgba(45,40,128,0.10);
font-family:Verdana;
border-radius:3px;
}
This is the HTML (can't show all of it because the table is massive):
<table id="tblAddress" class="tblData">
<tr>
<td class="auto-style3">
<asp:Label ID="lblACNO" runat="server" Text="ACNO" CssClass="Datalabelcolumn"></asp:Label></td>
<td class="auto-style2">
<asp:TextBox ID="txtACNO" runat="server" CssClass="autosuggest" Width="20%" ToolTip="This is a test tooltip"></asp:TextBox>
</td>
In ASP.Net, server tag<asp:Label> will be rendered as html <span>.
for <asp:TextBox> it is <input type='text'>
So please change your css selector
from
.tblData label {}
.tblData textbox{}
to
.tblData span{} or .tblData .Datalabelcolumn{}
.tblData input[type="text"]{} or .tblData .autosuggest {}
You are applying different css class to your Lable and TextBox inside your table (i.e Datalabelcolumn and autosuggest). So it will only apply those properties. Remove them and it will work. Or mention whatever style you need in your "Datalabelcolumn" and "autosuggest" css class for those controls.
add class="tblData" to td instead of table
basic demo
<td class="tblData">
<label>this is a label</label>
<textbox>this is textbox</textbox>
</td>

Expanding gridview's row

One of gridview's column is a "Content" column that can have few lines of text (it can be literal, textbox or label ).
In "default" mode i want it to show only the first line and a link button: "(more)" or "(read)".
Clicking on this link should expand the column and display full content.
What is the best way to do this?
Selecting first 10 characters of content text and using it as your link's text is better aproach. This will reduce size of data that retrieved from database like that :
SELECT ContentId, SUBSTRING(Content, 0, 10) AS Content
FROM ContentTable;
Then you can use template column for this column that includes a label and a link. Lbel for the description text, link for the details.
<asp:TemplateColumn>
<ItemTemplate>
<asp:Label
Text='<%# Eval("Content") %>'
runat="server"/>
<a href='<%# Eval("ContentId", "contentdetails.aspx?id={0}") %>'>More</a>
</ItemTemplate>
</asp:TemplateColumn>
This will help you.
http://www.asp.net/community/control-gallery/Item.aspx?i=1465
try this. http://mosesofegypt.net/post/BuildingjQueryAndASPNetAJAXEnabledControlsjQueryCollapsiblePanelExtenderPart2.aspx
Use the power of CSS!
Place this inside your gridview row. It will naturally push out the row to the height of your content, or the amount of rows required.
<div class="toggle">
<div class="toggle-header">
Toggle!
</div>
<div class="toggle-height">
<div class="toggle-transform">
<p>2nd line of text</p>
<p>3rd line</p>
<p>4th line</p>
<p>etc</p>
</div>
</div>
</div>
And use this CSS...
body {
font-family: sans-serif;
}
.toggle {
position: relative;
border: 2px solid #333;
border-radius: 3px;
margin: 5px;
width: 200px;
}
.toggle-header {
margin: 0;
padding: 10px;
background-color: #333;
color: white;
text-align: center;
cursor: pointer;
}
.toggle-height {
background-color: tomato;
overflow: hidden;
transition: max-height .6s ease;
max-height: 0;
}
.toggle:hover .toggle-height {
max-height: 1000px;
}
.toggle-transform {
padding: 5px;
color: white;
transition: transform .4s ease;
transform: translateY(-100%);
}
.toggle:hover .toggle-transform {
transform: translateY(0);
}
You may want to disguise the "toggle" with a textbox of your "(more)" line to expand the rest.
Let us know if it worked.

Categories