从SQL Server数据库表</select>动态设置<select>下拉列表

时间:2013-07-03 22:32:59

标签: c# asp.net sql sql-server html-select

我正在尝试设置一个下拉列表,以从SQL Server数据库中的表中提取。我正在使用带有代码的aspx将数据提交到SQL Server数据库。最终,我需要做的是在下拉列表中显示客户名称,然后将该数据提交到另一个数据库表。使用<asp:DropDownList>是一个选项,但我通过name属性提交数据,我无法为asp webform对象设置特定名称。我还没有使用我的形式的PHP,并希望尽可能保持清晰。

aspx html代码:

<select id="customerName" name="custName" class="txtbxList">
 <option></option>
 <option></option>
 <option></option>
</select>

asp DropDownSOurce和列表标签

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString='<%$ ConnectionStrings:csusaCentralConnection %>' SelectCommand="SELECT [customerNameDD] FROM [customerNameList]"></asp:SqlDataSource>
<asp:DropDownList ID="customerName" CssClass="txtbxList" runat="server" DataSourceID="SqlDataSource1" DataTextField="customerNameDD" DataValueField="customerNameDD"></asp:DropDownList>

我的代码隐藏:

string coName = Request.Form["custName"];
string generalInfo = @"INSERT INTO generalInfo(CustomerName)VALUES(@custName);

        SELECT SCOPE_IDENTITY();
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["csusaCentralConnection"].ConnectionString);

        SqlCommand cmd = new SqlCommand(generalInfo, conn);

        //NAME of input field in aspx file

        cmd.Parameters.AddWithValue("custName", coName);

        conn.Open();
        string rowIdentity = cmd.ExecuteScalar().ToString();
        conn.Close();

2 个答案:

答案 0 :(得分:0)

看起来您正在使用设计器来设置下拉列表数据源。以下是如何在代码中执行此操作:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            MyLinqToSqlDataContext db = new MyLinqToSqlDataContext();
            var result = from c in db.Customers
                         select g;
            customerName.DataSource = result.ToList();
            customerName.DataTextField = "Name";
            customerName.DataValueField = "ID";
            customerName.DataBind();
            ...
        }
   }

答案 1 :(得分:0)

从它的外观来看,你应该只需改变这一行:

string coName = Request.Form["custName"];

要:

string coName = customerName.SelectedValue;