将 DropDownList 项插入 SQL 数据库

我有一个 DropDownList,其中填充了 SQL 表中的数据。在网络表单中,当用户从该列表中选择一个项目时,我希望它将所选选项插入到另一个 SQL 表中,除了 DropDownLists 之外的所有内容都有效


我试过了 :

cmd.Parameters.AddWithValue("@*", ddl*.SelectedValue);

cmd.Parameters.AddWithValue("@*", ddl*.SelectedItem.Text);

ETC


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Windows.Forms;

using System.Data;

using System.Configuration;

using System.Text;

using System.Drawing;


namespace VXUK2

{

    public partial class booking_system : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {


            // SQL Query For DropDownList1 (CIT Company)

                SqlConnection con = new SqlConnection();

                con.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\****;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");

                con.Open();

                SqlCommand cmd = new SqlCommand("Select CIT_ID, CIT_CompanyName from CIT_Details", con);

                ddlCITCompany.DataSource = cmd.ExecuteReader();

                ddlCITCompany.DataTextField = "CIT_CompanyName";

                ddlCITCompany.DataValueField = "CIT_ID";

                ddlCITCompany.DataBind();


            // SQL Query for DropDownList2 (Site Details)

                SqlConnection con2 = new SqlConnection();

                con2.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\***;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");

                con2.Open();

                SqlCommand cmd2 = new SqlCommand("Select Site_ID, Site_Name from Site_Details", con2);

                ddlVisitingCentre.DataSource = cmd2.ExecuteReader();

                ddlVisitingCentre.DataTextField = "Site_Name";

                ddlVisitingCentre.DataValueField = "Site_ID";

                ddlVisitingCentre.DataBind();


        }

慕容森
浏览 80回答 1
1回答

aluckdog

您必须添加 not isPostBack,因为每次调用它的任何函数都会重新加载整个网页,因此每次您可以看到第一个数据都被选中。通过添加 !IsPostBack,页面将不会隐式重新加载数据。这可以解决您选择数据的问题。        protected void Page_Load(object sender, EventArgs e)        {            if(!IsPostBack)            {                //Your Code            }        }
打开App,查看更多内容
随时随地看视频慕课网APP