开发者

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, i.e. the previous value in the DB, if any, should be le开发者_开发问答ft untouched. 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(...); ...

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.


I would pass a null for the empty values into the db and use sql like:

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).

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:

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
                  }
              }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜