从C#

时间:2017-03-28 20:25:24

标签: c# asp.net webforms

非常需要帮助和赞赏。我正在开发一个项目,要求我从下拉菜单中选择一个值,然后将其插入到我的数据库中。下拉列表通过存储的proc和数据绑定加载,并且运行良好。但是当我按下按钮插入数据时,它只会插入默认文本 - 选择化学 - ,或者如果不存在,它将插入第一个选择中的任何内容。它永远不会看到其他项目。

我的内容代码:         

<table width="95%" style="padding-left:200px; padding-top:50px">
    <tr>
        <td style="font-size:large; font-weight:bold; padding-bottom:50px">
            <asp:DropDownList ID="ChemLot" runat="server">
            </asp:DropDownList>
        </td>
    </tr>
    <tr>
         <td colspan="2" align="center" >
            <asp:Label ID="lblchemMessage" runat="server" Visible="false" />
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center" >
        <br />
        <br />
             <asp:Button ID="AddChemLots" OnClick= "AddChemLot2" Text="Add New Chemical Lot" Font-Bold="true" runat="server" Height="50px" Width="250px" BackColor="Azure" />
        </td>

    </tr>
</table>

守则背后:

protected void AddChemLot2(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        String chemical = ChemLot.SelectedItem.Text.ToString();
        SqlConnection m_sqlConnection;
        string m_connectionString = ConfigurationManager.ConnectionStrings["ChemicalConnectionString"].ConnectionString;

        using (m_sqlConnection = new SqlConnection(m_connectionString))
        using (SqlCommand cmd = new SqlCommand("Insert_Chem"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = m_sqlConnection;
                m_sqlConnection.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@ChemName", chemical);
            }

            int check = cmd.ExecuteNonQuery();
            m_sqlConnection.Close();

我的Page_Load:

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

public void LoadList()
{
    string constr = ConfigurationManager.ConnectionStrings["ChemicalConnectionString"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Load_Chem"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                ChemLot.DataSource = cmd.ExecuteReader();
                ChemLot.DataTextField = "Chemical";
                ChemLot.DataBind();
                con.Close();
            }
        }

1 个答案:

答案 0 :(得分:1)

您应该使用SelectedItem.ValueSelectedValue代替

String chemical = ChemLot.SelectedItem.Value.ToString();

附加:在事件处理程序中检查以下条件没有意义,因为它始终是true

if (Page.IsPostBack)
{

正如我从您当前的编辑中看到的那样:您有以下内容。您根本没有指定DataValueField

ChemLot.DataTextField = "Chemical";
ChemLot.DataBind();

您应该同时指定

ChemLot.DataTextField = "Chemical";
ChemLot.DataValueField = <something>;
ChemLot.DataBind();