通过dropdownlist更新sql表

时间:2012-08-20 19:39:20

标签: c# asp.net sql

我有下拉列表(id="myDDL")。

我有更新我的sql表的方法(updateTable_byDDL),当我将手动值放在SET="bla"时,该方法很有用..

但是当我在SET= '"+ myDDL.Text.ToString() + "'中写入时,SQL更新上的列为空。

dropdownlist是从我放在page_load(在类中)之外的数组绑定的,我在页面加载上绑定它:

    myDDL.DataSource = array;
    myDDL.DataBind();

在aspx页面中,我可以很好地看到下拉列表中的数组值,但在我选择了我想要的项目后 - 然后单击按钮,该列将变为空。

我哪里错了?

2 个答案:

答案 0 :(得分:2)

如果你在page_load中绑定你的DDL,它将在你的页面加载时被绑定。因此,在快速猜测代码时,您所要做的就是添加一个if语句来检查page.isPostback

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        ddlDemo.DataSource = new string[] { "asdf", "jklö" };
        ddlDemo.DataBind();
    }
}

protected void btnDemo_Click(object sender, EventArgs e)
{
    Debug.WriteLine(ddlDemo.Text);
    SqlConnection con = null;
    using (con = new SqlConnection("YOUR CON STRING"))
    {
        SqlCommand com = new SqlCommand( "update tblXYZ set ABC = @A", con);
        SqlParameter param = new SqlParameter("A", System.Data.SqlDbType.YOURTYPE);
        param.Value = ddlDemo.Text;
        com.Parameters.Add(param);
        con.Open();
        int affectedRows = com.ExecuteNonQuery();
        Debug.WriteLine(affectedRows + " affected!");
        con.Close();
    }
}

在这个aspx页面中

<body>
  <form id="form1" runat="server">

    <asp:DropDownList ID="ddlDemo" runat="server">
    </asp:DropDownList>
    <asp:Button ID="btnDemo" runat="server" Text="Button" onclick="btnDemo_Click" />
  </form>
</body>

无论如何,在使用它来更新/插入/删除任何数据库记录之前,您应该始终检查用户输入!

答案 1 :(得分:1)

  1. 您应该myDDL.SelectedItem.Text
  2. 您应该使用参数来避免SQL注入
  3. 检查出来:

       YourUpdateCommand.CommandText = "UPDATE table SET column = @NewValue WHERE conditions";
    
       YourUpdateCommand.Parameters.Add("@NewValue", System.Data.SqlDbType.VarChar, 100); //or whatever
    
       YourUpdateCommand.Parameters["@NewValue"].Value = myDDL.SelectedItem.Text;
    
       YourUpdateCommand.ExecuteNonQuery();