Storing values in the DataValueField and DataTextField of a dropdownlist using a linq query

Posted by user1318369 on Stack Overflow See other posts from Stack Overflow or by user1318369
Published on 2012-04-07T04:50:23Z Indexed on 2012/04/07 5:28 UTC
Read the original article Hit count: 208

Filed under:
|
|

I have a website for dance academy where Users can register and add/drop dance classes.

In the web page to drop a particular dance, for a particular user, the dropdown displays her registered dances.

Now I want to delete one of the dances from the list. So I'll remove the row from the table and also from the dropdownlist. The problem is that everytime the item with the lowest ID (index) is getting deleted, no matter which one the user selects. I think I am storing the DataTextField and DataValueField for the dropdown incorrectly. The code is:

private void PopulateDanceDropDown()
{       
        // Retrieve the username
        MembershipUser currentUser = Membership.GetUser();
        var username = currentUser.UserName;

        // Retrive the userid of the curren user
        var dancerIdFromDB = from d in context.DANCER
                             where d.UserName == username
                             select d.UserId;

        Guid dancerId = new Guid();
        var first = dancerIdFromDB.FirstOrDefault();
        if (first != null)
        {
            dancerId = first;
        }

        dances.DataSource = (from dd in context.DANCER_AND_DANCE
                                    where dd.UserId == dancerId
                                    select new
                                    {
                                        Text = dd.DanceName,
                                         Value = dd.DanceId
                                    }).ToList();

        dances.DataTextField = "Text";
        dances.DataValueField = "Value";
        dances.DataBind();
    }

    protected void dropthedance(object o, EventArgs e)
    {
        String strDataValueField = dances.SelectedItem.Value;
        int danceIDFromDropDown = Convert.ToInt32(strDataValueField);
        var dancer_dance = from dd in context.DANCER_AND_DANCE
                           where dd.DanceId == danceIDFromDropDown
                           select dd;

        foreach (var dndd in dancer_dance)
        {
            context.DANCER_AND_DANCE.DeleteOnSubmit(dndd);

        }

        try
        {
            context.SubmitChanges();
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }       
    }

The problem is in the line:

String strDataValueField = dances.SelectedItem.Value;

The strDataValueField is always getting the minimum id from the list of dance item ids in the dropdown (which happens by default). I want this to hold the id of the dance selected by the user.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET