Jan Molbech
Jan Molbech

Reputation: 65

how to make asp dropdownlist accept null values when databinding

I am trying to populate a dropdownlist with the following LINQ statement

var beskeder = from b in db.beskeds
            join v in db.vedhaeftedeFilers on b.beskedId equals v.beskedId into x
            from v in x.DefaultIfEmpty()
            select new
            {
                beskedId = b.beskedId,
                tekst = b.tekst,
                dato = b.dato,
                behandlet = b.behandlet,
                medlemsid = b.medlemsid,
                dokumentid = b.dokumentId,
                filid = v.filId,
                filnavn = v.filnavn,
                filtype = v.filtype,
                data = v.data,
                DisplayText = "Besked fra bruger " + b.medlemsid.ToString() + ", " + b.dato
            };

DropDownList1.DataSource = beskeder;
DropDownList1.DataValueField = "medlemsid";
DropDownList1.DataTextField = "DisplayText";
DropDownList1.DataBind();

but i get a errormessage

The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.

i know it's because it won't accept null values. How do i make the dropdownlist accept null values. I would appreciate syntax examples

Upvotes: 1

Views: 1321

Answers (1)

Saeed Neamati
Saeed Neamati

Reputation: 35822

I propose that you change your strategy, and either remove items with null value, or set a default value for them, because you're using LINQ projection (you create new anonymous type). For example you can write:

 select new
 {
      medlemsid = b.medlemsid == null ? 0 : b.medlemsid
 };

in your projection, to convert nulls into 0

Upvotes: 1

Related Questions