[英]Error saving data from textbox to sql server table
I have created a WPF desktop application before and I was able to write up the code to save data from a textbox to a table I created in sql server 2012. I tried to create a WPF Web browser application and the same code was not working to save my data to my sql database.我之前创建了一个 WPF 桌面应用程序,我能够编写代码将文本框中的数据保存到我在 sql server 2012 中创建的表中。我尝试创建一个 WPF Web 浏览器应用程序,但相同的代码无法正常工作将我的数据保存到我的 sql 数据库中。 I am now trying to create another WPF desktop application and the same code that worked the last time is not working anymore.
我现在正在尝试创建另一个 WPF 桌面应用程序,但上次工作的相同代码不再工作。 Please look at my code and help.
请看我的代码和帮助。
private void savebuyers_Click(object sender, RoutedEventArgs e)
{
string connectionstring = null;
connectionstring = "Data Source=FRANCIS;Initial Catalog=Pam Golding;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionstring);
try
{
string query;
query = "insert into buyers (name,number,email) values ('" + namebuyers.Text + "'," + Convert.ToInt32(numberbuyers) + ",'" + emailbuyers.Text + "')";
SqlCommand command = new SqlCommand(query, con);
message1.Text = "Data Saved Successfully!";
con.Open();
command.ExecuteNonQuery();
con.Close();
}
catch
{
message1.Text = "Error While Saving Data!";
}
}
You have missed the Text
property of numberbuyers
.您错过了
numberbuyers
的Text
属性。 So it is unable to cast object of type TextBox
to type System.IConvertible
.因此无法将
TextBox
类型的对象转换为System.IConvertible
类型。 You can fix it like this:你可以像这样修复它:
Convert.ToInt32(numberbuyers.Text)
Also you should always use parameterized queries
to avoid Sql Injection
.此外,您应该始终使用
parameterized queries
来避免Sql Injection
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.