开发者

help inserting new row into a db using linq

Here is a snippet of my code:

else
    {
        SubCategory subCat = new SubCategory
        {
            SubCategoryName = name,
            Active = false,
            CategoryID=Convert.ToInt32(ddlCategory.SelectedValue)
        };
        db.SubCategories.InsertOnSubmit(subCat);
    }

    db.SubmitChanges();

The following line is causing an error:

CategoryID=Convert.ToInt32(ddlCategory.SelectedValue)

I have confirmed that the SelectedValue in my DDL is an int, and that the database is expecting an int, so I don't understand why asp.net gives me a YSOD saying "Input string was not in a correct format."

If I assign CategoryID 开发者_Python百科a number manually, it works.

EDIT: The problem was because I was populating the drop down list in my code behind and I didn't wrap it in a (!IsPostBack). So it was destroying the list, repopulating it and setting the index at 0 each time on post back.


so try this then

else
    {
        int cat = Convert.ToInt32(ddlCategory.SelectedValue);
        SubCategory subCat = new SubCategory
        {
            SubCategoryName = name,
            Active = false,
            CategoryID = cat
        };
        db.SubCategories.InsertOnSubmit(subCat);
    }


Where does ddlCategory come from? What's the value of ddlCategory.SelectedValue? When this gets run? Clearly it's not a valid integer-representing string at this point in time.


Maybe try

Int.Parse(ddlCategory.SelectedValue);


is the categoryID foreign key for another table? if yeah then try to pull the Category object and then assign it to the subCat.Category and see if it works (the relation must be set in the DBML designer)

one last thing: when exactly it throws the exception?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜