On page load the default value of the dropdownlist tell the user to select posible values.
Which is either Male or Female.If user did not select either of these values:Male or Female, the Genereate PatientNumber button should be disabled.
Otherwise the patient gender is generated base on the values select.
Currently if the dropdown is at default value i still can generate patientNumber.
Some one help me the cause of the error.i prefer the correct code.
protected void patient_num_Click(object sender, EventArgs e)
{
String gender = drl_gender.Text.ToString();
string patientNumber = " ";
RegistrationNumber Register_patient = new RegistrationNumber();
patient_num.Enabled = false;
if (gender=="Select Gender")
{
patient_num.Enabled = false;
}
else if (gender=="Male")
{
patient_num.Enabled = true;
patientNumber = Register_patient.GeneratePatientNumber(Gender.Male).ToString();
patientNumber = patientNumber.Replace("/", "-");
txtpatientNum.Text = patientNumber;
}
else
{
patient_num.Enabled = true;
patientNumber = Register_patient.GeneratePatientNumber(Gender.Female).ToString();
patientNumber = patientNumber.Replace("/", "-");
txtpatientNum.Text = patientNumber;
}
}
The problem in your code is that you are using the Text property of the DropDownList to determine what the user has selected(use SelectedValue instead). The Text property returns the text of the currently selected item but "" if no item is selected:
MSDN:
The Text property gets and sets the same value that the SelectedValuee
property does. The SelectedValue property is commonly used to
determine the value of the selected item in the ListControl control.
If no item is selected, an empty string ("") is returned.
Now have a look at your code(remember String.Empty when nothing is selected):
if (gender=="Select Gender")
{
patient_num.Enabled = false;
}
....
else
{
patient_num.Enabled = true;
// here we are!
patientNumber = Register_patient.GeneratePatientNumber(Gender.Female).ToString();
patientNumber = patientNumber.Replace("/", "-");
txtpatientNum.Text = patientNumber;
}
The solution:
Use a RequiredFieldValidator instead to ensure that the user has selected a gender. You can use the InitialValue property to tell it the value for your "-- please select --" item.
<asp:DropDownList id="DdlGender" runat="server" >
<asp:ListItem Text="-- please select --" Value="-1"></asp:ListItem>
<asp:ListItem Text="female" Value="1"></asp:ListItem>
<asp:ListItem Text="male" Value="2"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator id="RequiredGender"
InitialValue="-1"
ControlToValidate="DdlGender"
ErrorMessage="Please select gender!"
runat="server"/>
I would switch your logic over so that you explicity check for Male, Female then else.
if (gender=="Male")
{
...
}
else if (gender=="Female")
{
...
}
else
{
...
}
To answer your actual question, the value of your dropdown list probably isn't right. Maybe it's the casing or a stray character space. You could try something like
String gender = drl_gender.Text.Trim().ToLower();
and check for lowercase male, female. Put a break point on the line or add a watch and see what the actual value is.
What you want to do is set the button to disabled by default.
Then you should have an event hooked to the DropDownList:
protected void DropDownList_IndexChanged(object sender, EventArgs e)
{
var dd = (DropDownList) sender;
patient_num.Enabled = dd.SelectedIndex > 0;
}
Related
I want to implement "auto remember" feature of a form. This app is used by accountants who track cheque payments.
The accountant is entering a number of checks at a time and it will be time saving to maintain the project, beneficiary and project instead of choosing them every time you want to add a transaction.
The form looks like attached.
So far my attempts are failing and i keep seeing the dash entry '-' always at the top of each of the three dropdownfields as if i did nothing.
However 'watch' paramters shows that the Session values are properly retrieved and set.
I'm trying to save the previously entered values of those fields in a Session. Unless someone has another thought.
The nature of the fields in the asp file is as such
<asp:DropDownList ID="ddAccount" runat="server" Height="24px" OnSelectedIndexChanged="ddAccount_SelectedIndexChanged" >
<asp:ListItem>-</asp:ListItem>
</asp:DropDownList>
*<br />
<br />
<asp:DropDownList ID="ddProject" runat="server" Height="22px" >
<asp:ListItem>-</asp:ListItem>
</asp:DropDownList>
*<br />
<br />
<asp:DropDownList ID="ddBenificiary" runat="server" >
<asp:ListItem>-</asp:ListItem>
</asp:DropDownList>
*<br />
<br />
On Page_load I added the following Session getters and setters. I choose to populate first, i.e get the accounts, projects
etc then set the proper value based on the sessions.
protected void Page_Load(object sender, EventArgs e)
{
try
{
user = (User)Session["user"];
if (!IsPostBack)
{
if (Session["IsValidUser"] == null || Session["IsValidUser"].ToString() != "true")
Response.Redirect("Login.aspx", false);
/// Setting the Body tag.
Site1 m = (Site1)Master;
m.PageSection = "transactions";
//////////////////////////
Populate();
if (Session["BankAccount_ATx"] == null)
{
Session.Add("BankAccount_ATx", null);
}
else ddAccount.DataTextField = Session["BankAccount_ATx"].ToString();
if (Session["Project_ATx"] == null)
{
Session.Add("Project_ATx", null);
}
else ddProject.DataTextField = Session["Project_ATx"].ToString();
if (Session["BenefClient_ATx"] == null)
Session.Add("BenefClient_ATx", null);
else
ddBenificiary.DataTextField = Session["BenefClient_ATx"].ToString();
}
}
catch (Exception ex)
{
Response.Redirect("Login.aspx");
}
}
I save the chosen value in the session on the save button.
Session["BankAccount_ATx"] = ddAccount.SelectedValue;
Session["Project_ATx"] = ddProject.SelectedValue;
Session["BenefClient_ATx"] = ddBenificiary.SelectedValue;
Many thanks guys and gals
You want to set the selected value of the dropdownlist, like this:
if (Session["Project_ATx"] == null)
{
Session.Add("Project_ATx", null);
}
else {
// Find the list item in the drop down that mataches the value in your session
ListItem li = ddProject.Items.FindByValue(Session["Project_ATx"]);
//Check to see if the list item was found in the drop down
//If it's found, then make it the selected item
if ( li != null )
li.Selected = true;
}
If you were storing the Text value in Session then use this method instead:
FindByText
If you store your value using:
Me.Session.Item("LastDdlValue") = Me.YourDdlValue.SelectedValue
You can use this code in Page_Load event when Not Me.Page.IsPostBack:
If Not IsNothing(Me.Session.Item("LastDdlValue")) Then
Me.YourDdlValue.SelectedValue = Me.Session.Item("LastDdlValue")
End If
Please note that you need to populate your DropDownList before setting its .SelectedValue.
FindByText is the best method, alternatively you can iterate through the items in the dropdown using for loop compare each item with the value saved in session. If they are equal set selected index
for(int i=0;i<dropdownlist1.Items.count;i++)
{
if(dropdownlist1.Items[i].Text==Session["Project_ATx"].ToString())//use dropdownlist1.Items[i].Value if you have stored the dropdownlist item value instead of text
{
dropdownlist1.SelectedIndex=i;
break;
}
}
i have one dropdownlist of column intrestedFields,i have added ListItem attributes on that dropdownlist
now problems are when i put that intrest_field() method in postback , ListItem attributes are not showing ,
and when i put it outside of postback , listitem attributes are showing but my another dropdownlist items are not showing and also showing error " Object refrence not set to an intance of an object ".
i have tried with PreRender but same problem occurs.
.cs code
if (!IsPostBack)
{
intrest_field();
}
public void intrest_field()
{
ListItem l1 = new ListItem();
l1 = drpfield.Items.FindByValue("1");
l1.Attributes.Add("style", "color:gray;font-weight:bold;font-size:larger");
l1.Attributes.Add("disabled", "true");
l1.Value = "-1";
ListItem l2 = drpfield.Items.FindByValue("2");
l2.Attributes.Add("style", "color:gray;font-weight:bold;font-size:larger");
l2.Attributes.Add("disabled", "true");
l2.Value = "-1";
ListItem l3 = drpfield.Items.FindByValue("3");
l3.Attributes.Add("style", "color:gray;font-weight:bold;font-size:larger");
l3.Attributes.Add("disabled", "true");
l3.Value = "-1";
}
.aspx code
<asp:DropDownList ID="drpfield" runat="server" Height="20px" Width="190px"
AutoPostBack="True">
<asp:ListItem Value="1">Top Categories</asp:ListItem>
<asp:ListItem >Accounts</asp:ListItem>
<asp:ListItem Value="2">Financial </asp:ListItem>
<asp:ListItem>ITES</asp:ListItem>
<asp:ListItem Value="3">HR</asp:ListItem>
<asp:ListItem>Marketing</asp:ListItem> </asp:DropDownList>
after this l1.attributes.add style losts,
when i put intrest_field() in
protected void drpfield_PreRender(object sender, EventArgs e)
{}
it works but my another dropdownlist item are not showing
i.e after selecting item from drpfield,when i select items from my another dropdownlist country than it is not showing state.
without using dropdownlist drpfield it works
what could be a problem?
You are doing it wrong way. For example, You are finding item by value "1", changing to "-1" and after postback you are trying to find the item by Value "1", which doesn't exist anymore!
l1 = drpfield.Items.FindByValue("1");
... ... ...
l1.Value = "-1";
I would suggest not to change value to -1:
protected void Page_Load(object sender, EventArgs e)
{
intrest_field();
}
public void intrest_field()
{
ListItem l1 = new ListItem();
l1 = drpfield.Items.FindByValue("1");
l1.Attributes.Add("style", "color:gray;font-weight:bold;font-size:larger");
l1.Attributes.Add("disabled", "true");
//l1.Value = "-1";
ListItem l2 = drpfield.Items.FindByValue("2");
l2.Attributes.Add("style", "color:gray;font-weight:bold;font-size:larger");
l2.Attributes.Add("disabled", "true");
//l2.Value = "-1";
ListItem l3 = drpfield.Items.FindByValue("3");
l3.Attributes.Add("style", "color:gray;font-weight:bold;font-size:larger");
l3.Attributes.Add("disabled", "true");
//l3.Value = "-1";
}
And if there's a reason to set the value to -1, there should be way to do it in other way.
If you keep `l1.Value = "-1",you can check if l1 is null of course, but after postback it will be null and attributes will not be applied.
i had a DataList view which i add a check box in the Item Template
i want each item i select to increase some counter for examble once it's checked ..
i used the following code to handle that ,but the event function is never accessed ?!
protected void selectItemCheckBox_CheckedChanged(object sender, EventArgs e)
{
int selected = 0;
foreach (DataListItem i in DataList1.Items)
{
CheckBox chk = (CheckBox)i.FindControl("selectItemCheckBox");
if (chk.Checked)
{
selected++;
}
selectedItemCount.Text = Convert.ToString(selected);
}`
}
Currently you're looping over every checkbox for every checked checkbox which is inefficient and depending on your other code, may be causing trouble.
You're better off incrementing for each checkbox individually.
...DataList...
<ItemTemplate>
<asp:CheckBox id="selectItemCheckBox" runat="server"
AutoPostBack="True"
OnCheckedChanged="selectItemCheckBox_CheckedChanged" />
</ItemTemplate>
...DataList...
After a box is checked, update the total for just that checkbox using sender
protected void selectItemCheckBox_CheckedChanged(object sender, EventArgs e)
{
// Parse the total selected items from the TextBox.
// You may consider using a Label instead, or something non-editable like a hidden field
int totalChecked;
if (int.TryParse(selectedItemCount.Text, out totalChecked) = false)
totalChecked = 0;
// Get a reference to the CheckBox
CheckBox selectItemCheckBox = (CheckBox)sender;
// Increment the total
if (selectItemCheckBox.Checked == true)
totalChecked++;
// Put back in the TextBox
selectedItemCount.Text = totalChecked.ToString();
}
I have a devexpress calendar. The calendar has built in functions for grouping calendar by resource(which is location in my case). SO, I wrote my logic for making the calendar group by class name and provider too. The two work good individually. But when i was trying to place a radiobutton list so that user can select the way he want to group calendar,i had a problem.
This my radio button list and code behind event handler for it:
protected void filtertype_changed(object sender, EventArgs e)
{
if (filtertype.SelectedValue == "None")
{
// ASPxScheduler1.AppointmentDataSource = LoadAppointments();
classList.Visible = false;
providerslist.Visible = false;
classList.SelectedIndex = 0;
classList.SelectedIndex = 0;
//classList.SelectedValue = "0";
//providerslist.SelectedValue = "0";
ASPxScheduler1.GroupType = DevExpress.XtraScheduler.SchedulerGroupType.None;
}
else if (filtertype.SelectedValue == "Location")
{
// ASPxScheduler1.Dispose();
classList.Visible = false;
providerslist.Visible = false;
ASPxScheduler1.GroupType =
DevExpress.XtraScheduler.SchedulerGroupType.Resource;
}
else
{
ASPxScheduler1.GroupType = DevExpress.XtraScheduler.SchedulerGroupType.None;
classList.Visible = true;
providerslist.Visible = true;
}
}
This is my mark up for radio button
<asp:RadioButtonList ID="filtertype" runat="server"
OnSelectedIndexChanged="filtertype_changed" AutoPostBack="true" >
<asp:ListItem selected="true" Text="None" Value="None"></asp:ListItem>
<asp:ListItem Text="Location" Value="Location"></asp:ListItem>
<asp:ListItem>class Name and Provider</asp:ListItem>
</asp:RadioButtonList>
<asp:DropDownList ID="classList" runat="server" AutoPostBack="true"
Visible="false" ></asp:DropDownList>
<asp:DropDownList ID="providerslist" runat="server" AutoPostBack="true" Visible="false"
></asp:DropDownList>
classList and Provider List are the dropdownlists. So, what happens is when I change from Class and Provider radio button to location or none radio button, the calendar wont get refreshed and stores the values as per the dropdownlist and groups the calendar by location for those values only. So, once I change from classname and providers, I need to clear the dropdownlist values to 0(no item just white space). Can u just let me know how i can do this?
Throwing out the obvious here, but what about?:
DropDownList1.ClearSelection();
DropDownList1.Items.Clear();
Hi
I have site with two text boxes and dynamically create validation control. This is code from .aspx file:
<form runat="server">
<asp:TextBox AutoPostBack="true" ID="TextBox1" Text="" runat="server" Width="200px"
OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" Visible="True" Width="200px"AutoPostBack="true"></asp:TextBox>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:TextBox ID="ValidationTB" runat="server" Visible="true"></asp:TextBox>
</form>
This is my code-behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (TextBox2.Visible)
{
if (!String.IsNullOrEmpty(TextBox1.Text) && String.IsNullOrEmpty(TextBox2.Text))
{
RequiredFieldValidator RequiredFieldValidator1 = new RequiredFieldValidator();
RequiredFieldValidator1.Enabled = true;
RequiredFieldValidator1.ErrorMessage = "Second field required";
RequiredFieldValidator1.Display = ValidatorDisplay.Dynamic;
RequiredFieldValidator1.ControlToValidate = "TextBox2";
Panel1.Controls.Add(RequiredFieldValidator1);
RequiredFieldValidator1.Validate();
}
if (!String.IsNullOrEmpty(TextBox2.Text) && String.IsNullOrEmpty(TextBox1.Text))
{
RequiredFieldValidator RequiredFieldValidator1 = new RequiredFieldValidator();
RequiredFieldValidator1.Enabled = true;
RequiredFieldValidator1.ErrorMessage = "First field required";
RequiredFieldValidator1.Display = ValidatorDisplay.Dynamic;
RequiredFieldValidator1.ControlToValidate = "TextBox1";
Panel1.Controls.Add(RequiredFieldValidator1);
RequiredFieldValidator1.Validate();
}
if (!String.IsNullOrEmpty(TextBox2.Text) && !String.IsNullOrEmpty(TextBox1.Text))
{
if (Convert.ToDateTime(TextBox2.Text) < Convert.ToDateTime(TextBox1.Text))
{
ValidationTB.Text = null;
RequiredFieldValidator RequiredFieldValidator1 = new RequiredFieldValidator();
RequiredFieldValidator1.Enabled = true;
RequiredFieldValidator1.ErrorMessage = "Bad range of dates";
RequiredFieldValidator1.Display = ValidatorDisplay.Dynamic;
RequiredFieldValidator1.ControlToValidate = "ValidationTB";
Panel1.Controls.Add(RequiredFieldValidator1);
RequiredFieldValidator1.Validate();
}
}
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
RegularExpressionValidator RegularExpressionValidator1 = new RegularExpressionValidator();
RegularExpressionValidator1.ValidationExpression = #"^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$";
RegularExpressionValidator1.Enabled = true;
RegularExpressionValidator1.ErrorMessage = "Bad format of date";
RegularExpressionValidator1.Display = ValidatorDisplay.Dynamic;
if (!String.IsNullOrEmpty(TextBox1.Text))
{
RegularExpressionValidator1.ControlToValidate = "TextBox1";
Panel1.Controls.Add(RegularExpressionValidator1);
RegularExpressionValidator1.Validate();
}
if (!String.IsNullOrEmpty(TextBox2.Text))
{
RegularExpressionValidator1.ControlToValidate = "TextBox2";
Panel1.Controls.Add(RegularExpressionValidator1);
RegularExpressionValidator1.Validate();
}
}
}
TextBox ValidationTB is just to make validate on empty control.
This validation doesn't work, when I try:
1. To first textbox enter for example: 2009-09-09
2. To second textbox enter for example: 2009-10-09
Now, everything is OK.
3. I change my first textbox on for example 2009-12-09
I get error Bad range of dates - it's OK.
4. I correct first textbox on 2009-09-09, message disappear-OK.
5. Again enter to first textbox 2009-12-09 - I don't have error, but it should be.
What strange - in debug mode I can see, that in code:
if (Convert.ToDateTime(TextBox2.Text) < Convert.ToDateTime(TextBox1.Text))
{
ValidationTB.Text = null;
RequiredFieldValidator RequiredFieldValidator1 = new RequiredFieldValidator();
RequiredFieldValidator1.Enabled = true;
RequiredFieldValidator1.ErrorMessage = "Bad range of dates";
RequiredFieldValidator1.Display = ValidatorDisplay.Dynamic;
RequiredFieldValidator1.ControlToValidate = "ValidationTB";
Panel1.Controls.Add(RequiredFieldValidator1);
//In debug window: RequiredFieldValidator1.ControlToValidate = "TextBox2"
RequiredFieldValidator1.Validate();
}
instead of ValidationTB control, RequiredFieldValidator1.ControlToValidate is set to TextBox2 (it isn't empty, so I haven't error message).
Why TextBox2 is set to RequiredFieldValidator1.ControlToValidate instead of ValidationTB textbox and how I could solve this?
Thanks
Regards
It looks like what you are really wanting is a CompareValidator instead of what you are using.
Rewrite your 3rd IF block so that it looks like this:
if (!String.IsNullOrEmpty(TextBox2.Text) && !String.IsNullOrEmpty(TextBox1.Text))
{
Response.Write("Executing Block 3");
ValidationTB.Text = null;
CompareValidator CompareValidator1 = new CompareValidator();
CompareValidator1.Enabled = true;
CompareValidator1.ErrorMessage = "Bad range of dates";
CompareValidator1.Display = ValidatorDisplay.Dynamic;
CompareValidator1.Operator = ValidationCompareOperator.LessThan;
CompareValidator1.Type = ValidationDataType.Date;
CompareValidator1.ControlToCompare = TextBox2.ID;
CompareValidator1.ControlToValidate = TextBox1.ID;
Panel1.Controls.Add(CompareValidator1);
CompareValidator1.Validate();
}
This should give you the desired result.
Now... lets talk about some other things going on here.
First, unless you are just doing this as a proof of concept, then I highly encourage you to use the validators in a standard way. Nothing you are doing here requires that you add these validators in dynamically. Everything you want to accomplish can be achieved by simply adding the validators in the markup.
Second, your Event Handler for the text changed event is probably not going to do what you want. As it stands right now, it will fire too late in the page lifecycle to catch errors before your Page_Load event. Your current code will throw an exception if I enter "Blah" into both of the text boxes because it will attempt to convert those to DateTime types.
Lastly, when assigning ID's of existing controls you should use the ID property of that control instead of the Magic Strings you are using now. In this way you won't have to worry about changing the ID in multiple places if you decide to change it in markup.
Anyway, I hope this helps.
Shot in the dark, but try giving your validator controls IDs. RequiredFieldValidator1.ID = "HelloMyNameIsValidator1";