0

我正在尝试传递 Drop1.text (DropDownList) 的 selectedItem 以保存在 Emp_Name 字段中的 SQL 表 (TimeSheetDtls) 中,目前,下面的代码不起作用。当我单击按钮(button1_click 已添加到按钮)时,页面会发回,但不会更新表格或写出感谢声明。错误在哪里?

protected void button1_Click(object sender, EventArgs e)
{
    string name = Drop1.Text; // Scrub user data

    string connString = ConfigurationManager.ConnectionStrings["TimesheetDtlsConnectionString1"].ConnectionString;
    SqlConnection Conn = null;
    try
    {
        Conn = new SqlConnection(connString);
        Conn.Open();

        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = Conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "INSERT INTO TimeSheetDtls VALUES (@Emp_Name)";
            cmd.Parameters.AddWithValue("@Emp_Name", Drop1.SelectedItem);
            int rowsAffected = cmd.ExecuteNonQuery();
            if (rowsAffected == 1)
            {
                Response.Write("Thank you very much, " + Drop1.SelectedItem); //Success notification
            }
            else
            {
                Response.Write("There was an error, please try again."); //Error notification
            }
        }
    }
    catch (Exception ex)
    {
        //log error 
        //display friendly error to user
    }
    finally
    {
        if ( Conn != null)
        {
           Conn.Close(); //cleanup connection i.e close 
        }
    }
}
4

3 回答 3

0

有两种可能。

  1. 如果要插入所选文本,请dropdownlist使用:

    Drop1.SelectedItem.Text
    
  2. 如果要插入所选文本的值,请使用:

    Drop1.SelectedItem.Value
    
于 2012-07-06T12:32:08.960 回答
0

尝试Drop1.SelectedValue改用...

要在本地工作,请为您的连接字符串尝试以下格式:

<add name="LocalSqlServer" 
    connectionString="Initial Catalog=MyDB;Data Source=MyMachineName;Integrated Security=SSPI;"
        providerName="System.Data.SqlClient" />

对于远程服务器使用:

<remove name="MyConn" />
    <add name="MyConn" 
        connectionString="server=MyServerName;database=MyDB;uid=MyAdmin;pwd=MyPwd"
            providerName="System.Data.SqlClient" />
于 2012-07-06T12:23:47.180 回答
0

或者 Drop1.SelectedItem.Text,如果您真的想要文本。

于 2012-07-06T12:24:47.500 回答