1

I have a dropdown menu ddlInstructorAllocated in my asp.net web form which is getting all its items in the list from the database. I have inserted another item to be displayed as "Please Select Instructor" so users know what to do. When this form is saved, it populates the information entered to the database. The column that corresponds to ddlInstructorAllocated is not a mandatory field and can be left as NULL. What I'm trying to do is when "Please Select Instructor" is selected by default, its value to be NULL. I've tried many ways but can't seem to figure it out. below is one of the ways i tried. Please help. For the instances when an instructor is selected from the list, it's ID is returned, converted to a string and then saved into the DB.

        private void DisplayInstructors()
    {
        ListItem li;
        li = new ListItem("Please Select Instructor");
        li.Value = null;
        ddlInstructorAllocated.Items.Add(li);

        var instructors = EmployeeRepository.GetInstructors();

        foreach (var i in instructors)
        {
            ddlInstructorAllocated.Items.Add(new ListItem(string.Format("{0} {1}", i.FirstName, i.LastName), i.EmployeeID.ToString()));
        }
    }

The ID in the database is stored as int and i'm doing EmployeeID = int.Parse(ddlInstructorAllocated.SelectedValue) later on, i am getting an exception that input string was not in a correct format

MohammedAli_
  • 175
  • 3
  • 4
  • 15
  • Because the ID in the database is stored as int and i'm doing 'EmployeeID = int.Parse(ddlInstructorAllocated.SelectedValue)' later on, i am getting an exception that input string was not in a correct format – MohammedAli_ Feb 11 '13 at 03:48
  • You have to convert the selectedvalue to your int id property. – AD.Net Feb 11 '13 at 03:49
  • how can i convert null to int. can you please give an example? thanks – MohammedAli_ Feb 11 '13 at 03:51

2 Answers2

2
int id;
EmployeeID = int.TryParse(ddlInstructorAllocated.SelectedValue, out id)
                   ? id 
                   : (int?)null;

TryParse tries to parse the value into int, and you're assigning the value if you can successfully convert. If not you assign null value.

AD.Net
  • 13,352
  • 2
  • 28
  • 47
  • Thanks... I'm quite new to this. any chances you could comment on what the code does please? thanks a lot – MohammedAli_ Feb 11 '13 at 03:54
  • Please check this link: http://stackoverflow.com/questions/109859/what-does-datetime-mean-in-c it is the is syntactic sugar for Nullable. – Arindam Rudra Feb 11 '13 at 05:02
-1

Try placing your statment "Please select instructor" on index 0 of the drop down . When index zero is selected. Instead of placing null. You can do a few things here:

  1. Place something like n/a or an empty string.
  2. If u really want to out null try using dbnull or create your property nullable.

This shud help i think.

Tabish Sarwar
  • 1,505
  • 1
  • 11
  • 18