Search code examples
c#asp.netdrop-down-menuwebmethod

Selecting value from dropdownlist gives error in asp.net


I have set of code which fills my dropdownlist. So when I select some value from the list it works fine,

But when I go to the default selection which is --Select-- I get error as

the source contains no datarows

and it goes to the catch part

Below is my code. I Know I am missing something. Please suggest how to handle this

[WebMethod]
    public static MaintDetails[] GetMaintZone(string ddlState)
    {
        DataTable dt = new DataTable();
        List<MaintDetails> details = new List<MaintDetails>();

        if (HttpContext.Current.Session["dtStateMZ"] != null)
        {
            dt = (DataTable)HttpContext.Current.Session["dtStateMZ"];

            if (dt != null && dt.Rows.Count > 0)
            {
                try
                {
                    dt = dt.AsEnumerable().Where(r => r.Field<string>("JIOSTATECODE") == ddlState).CopyToDataTable();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dtrow in dt.Rows)
                        {
                            MaintDetails MZone = new MaintDetails();
                            MZone.MAINTID = dtrow["MAINTENANCEZONECODE"].ToString();
                            MZone.MAINTNAME = dtrow["MAINTENANCEZONENAME"].ToString();
                            details.Add(MZone);
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        return details.ToArray();
    }

Solution

  • The issue is with these lines:

    dt = dt.AsEnumerable().Where(r => r.Field<string>("JIOSTATECODE") == ddlState).CopyToDataTable();
    if (dt != null && dt.Rows.Count > 0)
    {
    

    The CopyToDataTable line is throwing the exception since it was called with (effectively) 0 rows. The solution, then, is to ensure that doesn't happen:

    var bob = dt.AsEnumerable().Where(r => r.Field<string>("JIOSTATECODE") == ddlState).ToList();
    if (bob.Count > 0)
    {
        dt = bob.CopyToDataTable();
    

    The above code copies the data into a temporary List, then ensures there is data in the List before calling CopyToDataTable.