使用下拉列表插入数据库

时间:2015-01-15 19:01:33

标签: c# asp.net insert

由于项目的数量很大,我有两个用sqldatasources填充的下拉列表。我的计划是从两个列表中选择一个项目,并将其插入表格中。基本上这些将显示新建立的关系的新记录。 这是我到目前为止所做的。

编辑:我的ASP文件以及我如何填充我的DropDownLists

 ServerID 
 <asp:DropDownList ID="DropDownList1" runat="server" 
    DataSourceID="SqlDataSource1" DataTextField="ServerID" 
    DataValueField="ServerID">
 </asp:DropDownList>
 <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:NewAppInventoryConnectionString %>" 
    SelectCommand="SELECT [ServerID] FROM [ServerDB_]"></asp:SqlDataSource>
  <br />

 DatabaseID
 <asp:DropDownList ID="DropDownList2" runat="server" 
    DataSourceID="SqlDataSource2" DataTextField="DatabaseID" 
    DataValueField="DatabaseID">
 </asp:DropDownList>
 <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
    ConnectionString="<%$ ConnectionStrings:NewAppInventoryConnectionString %>" 
    SelectCommand="SELECT [DatabaseID] FROM [ServerDB_]"></asp:SqlDataSource>

我的代码在文件后面

 string ServerDropDown = DropDownList1.Text;
 string DBDropDown = DropDownList2.Text;

 SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NewAppInventoryConnectionString"].ToString());
 SqlCommand cmd = new SqlCommand();

    cmd.CommandText = "INSERT INTO ServerDB_ (ServerID) VALUES (@ServerID)";
    cmd.CommandText = "INSERT INTO ServerDB_ (DatabaseID) VALUES (@DatabaseID)";
    cmd.Parameters.Add("@ServerID", SqlDbType.Int);
    cmd.Parameters["@ServerID"].Value = ServerDropDown;
    cmd.Parameters.Add("@DatabaseID", SqlDbType.Int);
    cmd.Parameters["@DatabaseID"].Value = DBDropDown;

    cmd.Connection = conn;

    conn.Open();

    cmd.ExecuteNonQuery();

    conn.Close();

我没有收到任何错误,但它没有像它应该的那样插入。我不确定该怎么做,我已经将这一切基于这样的教程:

Asp.Net inserting data into a database using a textbox

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

string ServerDropDown = DropDownList1.SelectedItem.Text;
string DBDropDown = DropDownList2.SelectedItem.Text;

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NewAppInventoryConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();

cmd.Connection = conn;

try{
    conn.Open();    
      //is ServerDB_ the table name?
    cmd.CommandText = "INSERT INTO ServerDB_ (ServerID, DatabaseID) VALUES (@ServerID, @DatabaseID)";

    cmd.Parameters.Add("@ServerID", SqlDbType.NVarChar);
    cmd.Parameters["@ServerID"].Value = ServerDropDown;

    cmd.Parameters.Add("@DatabaseID", SqlDbType.NVarChar);
    cmd.Parameters["@DatabaseID"].Value = DBDropDown;

    cmd.ExecuteNonQuery();
} 
catch(Exception ex)
{
    //do something with exception
}
 finally
{
    conn.Close();
}