我正试图将Drop1.text(DropDownList)的selectedItem传递到Emp_Name字段中的SQL表(TimeSheetDtls)中,但目前,下面的代码不起作用。当我点击按钮(按钮1_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
}
}
}
如果您真的想要文本,可以选择Drop1.SelectedItem.Text
。
请尝试使用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" />
有两种可能性。
-
如果要插入选定的
dropdownlist
文本,请使用:Drop1.SelectedItem.Text
-
如果您想插入所选文本的值,请使用:
Drop1.SelectedItem.Value