简体   繁体   English

将值从组合框中插入到SQL Server

[英]Insert value from combo box to SQL Server

In my DB I have two tables ( Employee and Team ). 在我的数据库中,我有两个表( EmployeeTeam )。 The Team table has two columns ( ID , TeamName ) and it's displayed in an asp.net page as a dropdown. Team表具有两列( IDTeamName ),并在asp.net页中作为下拉列表显示。

<asp:DropDownList ID="team_id" runat="server" CssClass="form-control"></asp:DropDownList>

From my asp.net page I need to insert a row into the employee table which includes teamID . 在我的asp.net页面上,我需要在employee表中插入一行,其中包括teamID

Below is set team combo box code 以下是团队组合框代码

private void SetTeamComboBox()
    {
        DataTable tableVariable = GetTeam();
        team_id.DataTextField = "TEAMNAME";
        team_id.DataValueField = "ID";
        team_id.DataSource = tableVariable;

        //MANUALLY ADD ROW
        DataRow dr = tableVariable.NewRow();
        dr["TEAMNAME"] = "Select TEAM";
        dr["ID"] = 0;
        tableVariable.Rows.InsertAt(dr, 0);
        team_id.SelectedIndex = 0;
        team_id.DataBind();
    }

public DataTable GetTeam()
    {
        SqlConnection oleconnectionVariable = new SqlConnection(conString);
        SqlCommand commandVariable = new SqlCommand();
        commandVariable.CommandText = "SELECT ID,TEAMNAME FROM TEAM";
        commandVariable.Connection = oleconnectionVariable;
        oleconnectionVariable.Open();
        SqlDataAdapter adapterVariable = new SqlDataAdapter(commandVariable);
        DataSet dataSet = new DataSet();
        adapterVariable.Fill(dataSet);

        adapterVariable.Dispose();
        commandVariable.Dispose();
        oleconnectionVariable.Dispose();
        return dataSet.Tables[0];//WE NEED TO GET THE DATATABLE  
    }

I need to insert the ID of the team but I'm getting an error on the following line. 我需要插入团队ID,但在下一行出现错误。

commandVariable.Parameters.AddWithValue("@TeamID",Convert.ToInt32(team_id.SelectedValue));

team id is always ZERO (see debugging image below) 团队ID始终为零(请参见下面的调试图)

错误图片

I think you are calling SetTeamComboBox() in Page_Load() event so every time DropDownBox control status changed. 我认为您在Page_Load()事件中正在调用SetTeamComboBox(),因此每次DropDownBox控件状态更改时。 The problem in postback which not handled. 回发中未解决的问题。

Solution: 解:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SetTeamComboBox();
        }
    }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM