Object refrence not set to an intance of an object - asp.net

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.

Related

How to assign programatically "include virtual" to asp.net dropdownlist items?

I have this dropdownlist in an ASP.NET page:
<asp:DropDownList ID="lstField1" runat="server">
<!--#include virtual="../path/to/myListOfValues.asp"-->
</asp:DropDownList>
Contents of "myListOfValues.asp" file:
<asp:ListItem value="%">Select value</asp:ListItem>
<asp:ListItem value="1">Value #1</asp:ListItem>
<asp:ListItem value="2">Value #2</asp:ListItem>
<asp:ListItem value="3">Value #3</asp:ListItem>
<asp:ListItem value="4">Value #4</asp:ListItem>
At some point of the page's execution, I change the items of this dropdownlist. But, eventually, i need to reload the items from the .asp file.
is there any way to "restore" the items from the .asp file, i.e. changing the dropdownlist's "innerHTML" or something like that?
Thanks in advance.
EDIT
I found a way:
1) Having a delimited string with the values i need to exclude from the items.
2) Splitting the delimited string
3) Looping the resultant array, and
4) Searching for the value in the dropdownlist. If the value is found, I disable it.
Something just like this:
'split the excluded items list
Dim arrExcludedItems() As String = myExcludedList.Split("|")
'enable all the dropdownlist's items.
For i As Integer = 0 To Me.lstField1.Items.Count - 1
Me.lstField1.Items(i).Enabled = True
Next
'search for the excluded item in the dropdownlist
'if it's found, disable the respective item.
For i As Integer = 0 To UBound(arrExcludedItems)
Me.lstField1.Items.FindByValue(arrExcludedItems(i)).Enabled = False
Next
Hope it helps for anyone.
Best regards,
I did some testing. I could not figure out how to rebind data from an asp file. But that does not mean you cannot achieve what you want. This snippet stores the original ListItems in ViewState so that you can bind the orignal ones later on.
<asp:DropDownList ID="lstField1" runat="server">
<!--#include virtual="/myListOfValues.asp"-->
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Bind new data" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Bind original data" OnClick="Button2_Click" />
Code behind
protected void Button1_Click(object sender, EventArgs e)
{
//create a new list to hold the original listitems
var list = new List<KeyValuePair<string, string>>();
//loop all the listitems and add them to the list
foreach (ListItem item in lstField1.Items)
{
list.Add(new KeyValuePair<string, string>(item.Value, item.Text));
Response.Write(item.Text);
}
//add the list to viewstate for later usage
ViewState["tempList"] = list;
//clear the list of its current items
lstField1.Items.Clear();
//add the new items to the dropdownlist
lstField1.Items.Add(new ListItem() { Text = "Item 1", Value = "1" });
lstField1.Items.Add(new ListItem() { Text = "Item 2", Value = "2" });
}
protected void Button2_Click(object sender, EventArgs e)
{
//load the list from viewstate and cast it back to a keyvalue list
var list = ViewState["tempList"] as List<KeyValuePair<string, string>>;
//clear the list of its current items
lstField1.Items.Clear();
//add the original items to the dropdownlist
foreach (var item in list)
{
lstField1.Items.Add(new ListItem() { Text = item.Value, Value = item.Key });
}
}

A logical Error in my Code

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;
}

Setting BackColor to items in DropDownList bound to ObjectDataSource inside DetailsView

how do you properly call methods inside custom binding expressions? Are there complications because the dropdownlist is inside a detailsview?
asp.net code:
<asp:DropDownList ID="ddlExceptionEditStatus" runat="server"
DataSourceID="odsExceptionsStatus"
DataTextField="Name"
DataValueField="StatusID"
SelectedValue='<%# Bind("StatusID") %>'
BackColor="<%# SetBackColorProp(Container.DataItem) %>">
</asp:DropDownList>
code behind:
protected System.Drawing.Color SetBackColorProp(object o)
{
System.Drawing.Color statusColor = System.Drawing.Color.White;
string statusName = o as string;
if (statusName != null)
{
statusColor = System.Drawing.ColorTranslator.FromHtml(FISBLL.StatusColors.GetColor(statusName));
return statusColor;
}
else
{
return statusColor;
}
}
Doesn't change the backcolor. but doesn't throw an exception.
So, I had two mistakes:
1) I needed to cast the Container.DataItem to the class object i was using for the ObjectDataSource. After casting, the BackColor for each item in the dropdownlist matched the StatusID of the casted Container.DataItem.
2) Unfortunately this gave all the items the same color, where as I wanted each item's color to reflect the their own value attached to the dropdownlist. This is because the dropdownlist has an objectdatasource outside the DetailsView that it's inside of. Therefor the selectedValue item of the dropdownlist dictated the colors for all the other items.
I decided to go with Tim's suggestion and tie the BackColor setting for each item in the databound event:
protected string GetColor(string name)
{
return FISBLL.StatusColors.GetColor(name);
}
protected void ddlExceptionEditStatus_DataBound(object sender, EventArgs e)
{
foreach (ListItem item in ((DropDownList)sender).Items)
{
item.Attributes.Add("style", "background-color:" + GetColor(item.Text));
}
}
And the correct behavior is shown:

CheckBox handling oncheck changed in ASP.net

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();
}

One DropDownList does not fire SelectedIndexChanged But Other Does

I am having a issue that I just can figure why it is happening
the situation is that I have two dropdownlists, both set up the same way
<asp:DropDownList ID="DocumentLink" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DocumentLink_Changed">
</asp:DropDownList>
<asp:DropDownList ID="PageLink" runat="server" AutoPostBack="true" OnSelectedIndexChanged="PageLink_Changed">
</asp:DropDownList>
Their events look like this
protected void DocumentLink_Changed(object sender, EventArgs e)
{
DropDownList DocumentLink = sender as DropDownList;
LinkParam = DocumentLink.SelectedValue.ToString();
DescriptionParam = DocumentLink.SelectedItem.Text;
}
protected void PageLink_Changed(object sender, EventArgs e)
{
DropDownList PageLink = sender as DropDownList;
LinkParam = PageLink.SelectedValue.ToString();
DescriptionParam = PageLink.SelectedItem.Text;
}
In the case of the DropDown called "PageLink" the event handler fires. However for the "DocumentLink" the event handler does not. In debug I see that page load is fired but the event drops off after the page load and never enters DocumentLink_Changed
As an point of interest if I use a telerik radComboBox in place of the DropDownList using the same set-up it does work.
<telerik:RadComboBox ID="DocumentLink" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DocumentLink_Changed">
</telerik:RadComboBox>
with the event handler like this
protected void DocumentLink_Changed(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
unfortunately I need to use Dropdownlists for my project.
What could be causing this?
UPDATE
I have taken the working dropdownlist and used the LINQ binding for the dropdownlist that did not work. The result was that the PageLink dropdownlist began to behave just like the 'DocumentLink' dropdownlist. This makes me believe that the issue might be in the binding method but they the two are very similar and I do see results in the dropdownlist
this is my binding
if (selectedValue == 3)
{
DropDownList select = lvLinks.InsertItem.FindControl("PageLink") as DropDownList;
List<IPW_Links_get_document_listResult> getList = (from i in lqContext.IPW_Links_get_document_list(0, "my stuff") select i).ToList();
select.DataSource = getList;
select.DataTextField = "DocumentName";
select.DataValueField = "FolderPath";
select.DataBind();
}
if (selectedValue == 2)
{
DropDownList select = lvLinks.InsertItem.FindControl("PageLink") as DropDownList;
List<IPW_Links_get_available_pagesResult> getList = (from i in lqContext.IPW_Links_get_available_pages(PortalId) select i).ToList();
select.DataSource = getList;
select.DataTextField = "TabName";
select.DataValueField = "TabPath";
select.DataBind();
}
do check if you have any statements in the PageLoad event that alters the dropdownlists. If you have a databinding statement or a selection reset statement in the page load event , then make sure it is under the if not ispostback conditional snippet.

Resources