Using SqlCommand , how to add multiple parameters to its object , insertion via winform in sql table

前端 未结 4 1595
盖世英雄少女心
盖世英雄少女心 2020-12-29 17:12

I have ten textboxes in my winform, and i need to save the text typed in these textboxes into 10 columns of a sql database table. so, for this shall i write :



        
4条回答
  •  Happy的楠姐
    2020-12-29 18:15

    You can use an extension method, like this:

    public static class DbCommandExtensions
    {
        public static void AddInputParameters(this IDbCommand cmd,
            T parameters) where T : class
        {
            foreach (var prop in parameters.GetType().GetProperties())
            {
                object val = prop.GetValue(parameters, null);
                var p = cmd.CreateParameter();
                p.ParameterName = prop.Name;
                p.Value = val ?? DBNull.Value;
                cmd.Parameters.Add(p);
            }
        }
    }
    

    Then call it like this:

    cmd.AddInputParameters(new { a = textBox1.Text, b = TextBox2.Text, /* etc */ });
    

    I've used that in a few projects with no problems.

提交回复
热议问题