简体   繁体   English

根据来自表单的用户输入,将一个表的主键插入另一个表

[英]Insert primary key from one table into another based on user input from a form

I have a form with an asp:DropDownList that populates its contents from the Item_Description column in the Item table. 我有一个带有asp:DropDownList的表单,该表单从Item表的Item_Description列填充其内容。

I would like to allow users to select an item from the drop-down list, and when the form is submitted, insert the ItemID value for the selected item into the Orders table using C#/T-SQL. 我想允许用户从下拉列表中选择一个项目,并在提交表单后,使用C#/ T-SQL将所选项目的ItemID值插入到Orders表中。

I could theoretically accomplish this with some lengthy if/else statements, but this seems too simple to require so much code. 从理论上讲,我可以使用一些冗长的if / else语句来完成此操作,但这似乎太简单了以至于不需要那么多代码。

I am able to update other tables by assigning asp:Textbox values to parameters and inserting them upon submission. 我可以通过为参数分配asp:Textbox值并在提交时插入它们来更新其他表。 I just can't seem to figure out how to pass the ItemID to the Orders table when a user selects a related item from the list. 当用户从列表中选择相关项目时,我似乎似乎无法弄清楚如何将ItemID传递给Orders表。

PS I have already established a connection to my database, protected against SQL injection, etc. PS我已经建立了到数据库的连接,可以防止SQL注入等。

Drop-down list: 下拉列表:

ID="ddlItems" ID =“ ddlItems”

Code for tables: 表格代码:

CREATE TABLE Item
(
    ItemID int primary key,
    Item_Description varchar(255)
); 

CREATE TABLE Orders
(
    OrderID int primary key,
    Order_Item varchar(255)
);

Code-behind method for Submit button click event: 提交按钮单击事件的代码隐藏方法:

protected void Submit_Click(object sender, EventArgs e)
{
    SqlConnection conn;
    SqlCommand comm;
    SqlDataReader reader;
    conn = new SqlConnection("Server=*omitted*");
    comm = new SqlCommand("INSERT INTO Orders VALUES @ItemID;", conn);

    comm.Parameters.Add("@ItemID", System.Data.SqlDbType.Int);
    comm.Parameters["@ItemID"].Value = <<<This is where I need help>>>;

    try
    {
        conn.Open();
        reader = comm.ExecuteReader();
        reader.Close();
    }
    catch
    {
        results.Text = "Error adding data. ";
    }
    finally
    {
        // Close the connection
        conn.Close();
        results.Text = "Added data.";
    }
}

Drop-down List binding: 下拉列表绑定:

<asp:DropDOwnList ID="ddlItems" runat="server" AutoPostBack="True" AppendDataBoundItems="True" DataSourceID="SqlDataSource1" DataTextField="Item_Description" DataValueField="Item_Description">
<asp:ListItem Value=""></asp:ListItem>
<asp:DropDownList>

As per you Quetion I think You Insert Query Does't Require Where Condition Just Remove the Condition 根据您的问题,我认为您插入查询不需要条件只要删除条件

Bind DropDown Code 绑定下拉代码

       DataSet ds = new DataSet();
        Cmd.CommandText = sqlcmd;
        Cmd.CommandTimeout = this.Timeout;
        Cmd.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter sda = new SqlDataAdapter();
        sda.SelectCommand = Cmd;
        sda.Fill(ds);


        ddl.DataSource = ds.dt[0];
        ddl.DataTextField = ds.dt[0][COlumnname]
        ddl.DataValueField = ds.dt[0][ColumnName];
        ddl.DataBind();
I would join the Item and Orders table by ItemID, not Item_Description.

CREATE TABLE Item
(
    ItemID int primary key,
    Item_Description varchar(255)
); 

CREATE TABLE Orders
(
    OrderID int primary key,
    ItemID int 
);

I would set a referential constraint on ItemID.  ddlItems should have DataValueField of ItemID and DataTextField of Item_Description.

Assuming ItemID and OrderID are auto-incrementing, you could write:

SqlCommand comm = new SqlCommand("INSERT INTO Orders (ItemID) VALUES (@itemID)");

This is also assuming only one ItemID could be associated with an Order, otherwise, you would need Item, Order, and OrderItemAsc tables. 这也假设只有一个ItemID可以与Order关联,否则,您将需要Item,Order和OrderItemAsc表。

I am assuming that you are binding your drop downlist with the Item table. 我假设您将下拉列表与Item表绑定在一起。

So follow this approach. 因此,请遵循此方法。

  1. Query would be (For binding drop downlist data from item table) 查询将是(用于绑定项目表中的下拉列表数据)

    select * from item

  2. In C# 在C#中

    ddlItems.DataSource = "your data table in which you are taking result of above query"; ddlItems.DataBind();

(I think you already have done the above steps) (我认为您已经完成了上述步骤)

  1. Now just add two attribute to your drop down list in source like this. 现在,只需在源代码的下拉列表中添加两个属性,如下所示。

     <asp:DropDownList ID="ddlItems" runat="server" DataTextField="Item_Description" DataValueField="ItemID " > 

  2. Now you can directly access the id for selected item in drop down from c# code 现在,您可以从c#代码的下拉列表中直接访问所选项目的ID

    comm.Parameters["@ItemID"].Value= ddlItems.SelectedItem.Value;

Edit 编辑

Now looking at your edited question you just need to change DataValueField="ItemID" only :) 现在查看您已编辑的问题,您只需要更改DataValueField="ItemID" :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#:是否有任何C#函数可以将主键从一个表插入另一个表 - C# : Is there any C# function to insert primary key from one table into another 如何将由自动递增创建的一个表中的主键作为外键插入第二个表中? - How to insert primary key from one table which created by auto increment, into a second table as forign key? 从SQL插入查询中获取新记录主键ID以将相同值插入另一个表中? - Get the new record primary key ID from SQL insert query to insert same value into another table? 如何将一个表中的主(代理)键添加到另一个表的外键中? - How to add a primary (Surrogate) key from one table into a foreign key of another table? 将生成的主键作为外键插入控制器的不同表中 - Insert generated primary key as foreign key in different table from controller 从一张表插入到另一张表 - Insert from one table into another 将数据插入表并从增加的主键中获取ID - Insert data into table and get ID from increased primary key 插入到两个表中,其中一个表具有自动增量主键,并且同一键用作另一表中的外键 - Insert into two tables with one table having an auto increment primary key and that same key is used as a foreign key in another table 将一个表中的单个外键字段的多个值插入到另一个表中 - Insert multiple values for single foreign key field from one table into another table 将所选值从一个表插入另一个表 - Insert selected values from one Table to another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM