Dynamically populating and setting value in dropdownlist in ASP.Net - c#

I have a form where I have 4 dropdowns Country, State, District and City. Country is populated on form load and rest are populated on selected index changed event. The sequence is On Country's selected index changed States are populated. On State-> Districts populated and on Districts -> Cities are populated.
For saving it worked fine but when i was updating value, it shows null reference error. On debugging I got, the dropdowns are not populated, whereas I was trying set values. Below is my code.
using (var manager = new LocationManager())
{
var dt = manager.GetLocationById(i);
if (dt.Rows.Count == 1)
{
Countries.SelectedValue = Countries.Items.FindByText(dt.Rows[0]["Country"].ToString()).Value;
BindStates(Convert.ToInt32(Countries.SelectedItem.Value));
States.SelectedValue = States.Items.FindByText(dt.Rows[0]["State"].ToString()).Value;
BindDistricts(Convert.ToInt32(States.SelectedItem.Value));
Districts.SelectedValue = Districts.Items.FindByText(dt.Rows[0]["District"].ToString()).Value;
BindCities(Convert.ToInt32(Districts.SelectedItem.Value));
Cities.SelectedValue = Cities.Items.FindByText(dt.Rows[0]["City"].ToString()).Value;
Pincode.Text = dt.Rows[0]["Pincode"].ToString();
ViewState["Id"] = dt.Rows[0]["LocationId"].ToString();
}
}
I am getting error: {"Object reference not set to an instance of an object."} at method
BindStates(Convert.ToInt32(Countries.SelectedItem.Value));

I think the problem is not with the population of drop downs, but with finding values, when
Countries.Items.FindByText(dt.Rows[0]["Country"].ToString())
wont find any matching value it will return null. So applying 'Value' property on null is giving the error.
you can put a null check before selecting it.
something like below:
countryDropDown.SelectedValue = countryDropDown.Items.FindByText(dt.Rows[0]["Country"].ToString()) != null ? countryDropDown.Items.FindByText(dt.Rows[0]["Country"].ToString()).Value : countryDropDown.Items.FindByText("-Please select-").Value;

Check if Countries.SelectedItem != null

#Amit Ranjan: Bind all values in page init method and at page load make the perticular value selected for all drop downs:
you are getting null reference because, there is no value already bind to the drop down.
At page init bind all values to dropdown
India
US
UK
asp:DropDownList>
At page load
DropDownList .SelectedValue= dt.Rows[0]["Country"].ToString()).Value;

Related

AJAX ModalPopupExtender & Gridview row values

I've not really used the MPE before & currently have a need to, what I'm slightly confused about is losing reference to the initial control that triggers the function.
I have a gridview with a dropdownlist and onselectedindexchanged set to call a function when a value has been selected, when processed one value i grab is the RowID into a variable, out of 9 list items only one requires the pop up (Ok = proceed & Cancel = Return) & when this is triggered I lose all reference to the given grid row which is referenced via;
DropDownList ddlid = (DropDownList)sender;
GridViewRow gvrow = (GridViewRow)ddlid.NamingContainer;
RowID = (Int32.Parse(GridView1.DataKeys[gvrow.RowIndex].Values[0].ToString()));
Can anyone shed any light or have an idea on how I can keep track of the gridview row?
Thanks
IchBinDicky
Used session object in the code behind (point of loss) in the end as it fit a few other issues I'd encountered at the same time;
public static string TabIndxValue
{
get
{
object value = HttpContext.Current.Session["TabIndxValue"];
return value == null ? "" : (string)value;
}
set
{
HttpContext.Current.Session["TabIndxValue"] = value;
}
}

Value for ASPX Dropdown list is not being set to correct value

I am trying to bind a drop down list using this C# code:
var ctype = db.ComplaintTypes
.Select(r => new { r.ComplaintTypeID, r.Description })
.ToList();
ddlComplaintType.DataSource = ctype;
ddlComplaintType.DataTextField = "Description";
ddlComplaintType.DataValueField = "ComplaintTypeID";
ddlComplaintType.DataBind();
Code populates the dropdown however the index count is off by 1. So ComplaintTypeID has a value of 1 in the data table but the code is returning a value of 0. Which causing the app to crash for an invalid ComplaintTypeID.
If I add ddlComplaintType.Items.Insert(0, "** Please Select**");
It works but that causing my aspx required field validator to not work. How can I correct the code to show the correct datavalue ?

How can I remove my selected item duplicate and provide a Please Select option AFTER my selected item in my DropDownlist is bound?

In my Page Load method I prepopulate the DropDownList with lookups from my database.
ddRelationship.DataSource = _dal.GetStandardLookups(Guid.Parse(fhsConstants.fhsRelationship));
ddRelationship.DataTextField = "LookupDescription";
ddRelationship.DataValueField = "LookupValue";
ddRelationship.DataBind();
ddRelationship.Items.Insert(0, new ListItem("Please Select", "0"));
I then set the existing value from the list in with Populate from database method
if (String.IsNullOrEmpty(_dal.GetStandardLookupDescription(CurrentDependant.Relationship)) == false)
{
ddRelationship.SelectedItem.Value = _dal.GetStandardLookupValue(CurrentDependant.Relationship);
ddRelationship.SelectedItem.Text = _dal.GetStandardLookupDescription(CurrentDependant.Relationship);
}
else
{
ddRelationship.SelectedIndex = 0;
}
The issue I am having is that, if populate from database I am no longer able to see my 'Please Select' option and my selected option appears twice! I.e. If the populate from database method is not called I can see 'Please Select', 'Mother', 'Father'... If I populate from database and my value is Father then I can see 'Father', 'Mother', 'Father'...
Is there a way to stop this duplication and retain my Please Select option? Thanks
I believe this is working for me now, albeit that it uses description instead of value:
ddRelationship.ClearSelection();
ddRelationship.Items.FindByText(_dal.GetStandardLookupDescription(CurrentDependant.Relationship)).Selected = true;

How to allow null to be added to database

I have an issue where I add data to my database from my WCF application, but I get the following error when stepping over the code snippet below:
Nullable object must have a value.
foreach (var sectionGroup in quote.Items.First().SectionGroups)
bills.Add(new ListOfBills
{
Cost = (double)sectionGroup.Cost,
PricePerMeter = sectionGroup.Price_m,
GroupName = sectionGroup.SectionGroup.Name,
Length = sectionGroup.Length,
Quantity = (double)sectionGroup.Quantity,
StockCode = sectionGroup.StockItem.StockCode,
StockDescription = sectionGroup.StockItem.Description,
TruckSection = sectionGroup.SectionGroup.Section,
Weight = (double)sectionGroup.Weight,
Width = sectionGroup.Width
});
return bills;
The thing is that from my WPF application where I access the data and display the information in a datagrid, some of the rows will have be null depending the user's selection from the comboboxes.
So my question is that, is there a way to not display the null rows of data or just add them to the database with the value as null and how can I get past the nullable error from above?
Thanks in advance! :)
You can try to use DBNull.Value to represent NULL in DB, so it should solve your error.
In every place you want to add a null add DBNull instead, here's an example:
Cost = sectionGroup.Cost == null ? DBNull.Value : (double)sectionGroup.Cost

How to get selected value from DevExpress comboBox

I'm trying to get the text from the selected value in the combo box by using:
lblMessage.Text = cmbArchivoModificado.SelectedItem.Text;
I've already set the valuefield and textfield on the combobox settings, but visual studio keep telling me this:
nullreferenceException was unhandled by user code.
Object reference not set to an instance of an object.
Usually the problem, when the ASPxComboBox's SelectedItem / SelectedIndex is incorrect, occurs when the ASPxComboBox.ValueType property is specified incorrectly.
Ensure that the ValueType is set, corresponding to the "Data Type Mappings (ADO.NET)" table.
Try to use the ASPxComboBox.Value property instead:
lblMessage.Text = cmbArchivoModificado.Value != null
? cmbArchivoModificado.Value.ToString()
: string.Empty;
Looks to me like you need to first check whether cmbArchivoModificado.SelectedItem is null.
lblMessage.Text = cmbArchivoModificado.SelectedItem == null ? "NA"
: cmbArchivoModificado.SelectedItem.Text;
Get the value on this way:
var value = comboboxExample.SelectecText;
or
var value = comboboxExample.EditValue;

Categories