[英]How do I insert values from many textboxes into my database with minimal code?
Please kindly bear with me. 请您多多包涵 I need to insert the values from a lot of textboxes and combo-boxes into a DB. 我需要将许多文本框和组合框中的值插入数据库。 Now, if any of the textboxes or combo-boxes is EMPTY, I want that to be skipped, ie the previous value in the DB, if any, should be left untouched. 现在,如果任何文本框或组合框为EMPTY,我希望跳过该文本框,即,应保持数据库中的上一个值(如果有)不受影响。 Something like updating a profile. 例如更新个人资料。 I will be so glad if you can come to my rescue. 如果你能来救我,我会很高兴。
I don't want to be writing endless cmd.Parameters.AddWithValues(...); 我不想写无尽的cmd.Parameters.AddWithValues(...); ... ...
Thank you in anticipation. 谢谢您的期待。
Edit: I want a situation, for instance, if a user tries to enter new records but left some of the fields empty, I will just replace what is already in the DB with the values he/she enters. 编辑:例如,我想要一种情况,如果用户尝试输入新记录但将某些字段留空,我将用他/她输入的值替换数据库中已有的内容。 But if a field is empty, I want to leave what is already in the DB untouched choosing not to replace it with an empty value. 但是,如果一个字段为空,则我希望不更改数据库中已有的内容,选择不将其替换为空值。 Thanks. 谢谢。
I am using C# within VS2010 and the the database is MSSQL. 我在VS2010中使用C#,数据库为MSSQL。
I would pass a null for the empty values into the db and use sql like: 我会将一个空值传递给db并使用sql来像这样:
Here is an example for Transact SQL for Microsoft SQL Server, using the isnull function, that checks if the first parameter is null and if sets a column to itself (ie not change it). 这是用于Microsoft SQL Server的Transact SQL的示例,该示例使用isnull函数,该函数检查第一个参数是否为null以及是否将列设置为其自身(即,不对其进行更改)。
update the_table
set
col_x = isnull(@some_value_x, col_x),
col_7 = isnull(@some_value_y, col_y)
.
.
.
in the C# code you could use: 在C#代码中,您可以使用:
string some_value_x = textbox_x.Text.Trim();
if(string.IsNullOrWhitespace(some_value_x))
some_value_x = null;
I think the preferred method is to load existing values from the DB into the text boxes and then save them back into the db on the update, so users can blank out a field if they want. 我认为首选方法是将数据库中的现有值加载到文本框中,然后在更新时将其保存回数据库中,以便用户可以根据需要清空该字段。 This will simplify your logic and be more consistent with current practices. 这将简化您的逻辑,并与当前实践更加一致。
What about something like this: 像这样的事情呢:
string s;
foreach (Control cc in this.Controls)
{
if (cc is ComboBox || cc is TextBox)
{
if (!string.IsNullOrEmpty(cc.Text))
{
s = cc.Text;
//Do something with the value
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.