选定项目 - 列表框插入数据库

时间:2017-01-13 11:19:29

标签: c# sql-server database listbox insert-into

我在向数据库添加值时遇到了一个小问题。

C#和SQL Server

我有这个程序:

ALTER PROCEDURE [AB].[AddMovie]
    @Actors nvarchar(255),
    @Director nvarchar(100),
    @Title nvarchar(255),
    @Year char(4),
    @Length nvarchar(5),
    @Description nvarchar(255),
AS
BEGIN
    INSERT INTO AB.Movie (Title, Year, Lenght, Description, Actors, Director) 
    VALUES (@Title, @Year, @Lenght, @Description, @Actors, @Director)
END;

ADDCATEGORY_TYPE

ALTER PROCEDURE [AB].[AddCategoryType]
    @Category nvarchar(50),
    @Title nvarchar(255)
AS
BEGIN
    INSERT INTO AB.CategoryType (CategoryID, MovieID) 
    VALUES ((SELECT CategoryID 
             FROM ab.Category 
             WHERE name = @Category), 
            (SELECT Movie ID 
             FROM AB.Movie 
             WHERE Title = @Title));
END;

我通过表适配器加载电影类别:

private void LoadCategory()
{
    string kom = "";
    CinemaDataSetTableAdapters.LoadCategoryTableAdapter category = new CienamDataSetTableAdapters.LoadCategoryTableAdapter();
    category.Fill(cinemaDataSet.LoadCategory, ref kom);
}

进入列表框。

我想做什么?

我想将listbox中的SELECTEDITEMS INSERT到表中(CategoryID FK,MovieID FK),但如果我在C#中使用:

private void AddMovieButton_Click(object sender, EventArgs e)
{
        CinemaDataSetTableAdapters.QueriesTableAdapter tmp = new CinemaDataSetTableAdapters.QueriesTableAdapter();
        tmp.AddMovie(ActorsTextBox.Text, Director.TextBox.Text, TitleTextBox.Text, YearTextBox.Text, LenghtTextBox.Text, Description.TextBox.Text);

        List<string> list = new List<string>();

        foreach (var items in CategorylistBox.SelectedItems)
        {
            list.Add(items.ToString());
        }

        foreach (var items in list)
        {
            CinemaDataSetTableAdapters.QueriesTableAdapter kType = new CinemaDataSetTableAdapters.QueriesTableAdapter();
            kType.AddCategoryType((items), TitleTextBox.Text);
        }
    }

我收到错误:

  

附加信息:无法将值NULL插入列&#39; CategoryID&#39;,table&#39; JiPPZ507.AB.CategoryType&#39 ;;列不允许空值。 INSERT失败。

我在网站上看,我发现了很多信息,但它仍然不起作用:/

我也试过:

        List<string> selectedFields = CategorylistBox.SelectedItems.OfType<string>().ToList();
        foreach (var items in selectedFields)
        {

            string selectedItem = items.ToString();
            CinemaDataSetTableAdapters.QueriesTableAdapter kType = new CienamDataSetTableAdapters.QueriesTableAdapter();
            kType.AddCategoryType((selectedItem), TitleTextBox.Text);

        }

我不明白:

  

无法将值NULL插入列&#39; CategoryID&#39;,table&#39; JiPPZ507.AB.CategoryType&#39 ;;列不允许空值。 INSERT失败

但没有任何内容添加到数据库中的表CategoryType:(

0 个答案:

没有答案