我们可以使用foreach清除表单中的所有文本框,而无需为每个文本框键入代码以清除它们。
com.Parameters.Add(new SqlParameter("@",objPlayrInjr_P));
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "SPname";
com.Connection = connection object;
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("@SqlParameterName",objectName.propertyName));
}
我需要一种方法通过循环将sqlParameters
添加到Command
对象,就像我在清除文本框时所做的那样。所以不需要为每个语句编写代码,它将由循环完成。
答案 0 :(得分:3)
一种方法是将参数名称和值放在Dictionary<string, object>
然后
foreach (KeyValuePair<string, object> param in params)
{
com.Parameters.AddWithValue(param.Key, param.Value);
}
答案 1 :(得分:3)
以下是使用注释的内容:
[AttributeUsage(AttributeTargets.Property)]
public class ParameterAttribute : Attribute
{
public string ParameterName { get; private set; }
public ParameterAttribute(string parameterName)
{
ParameterName = parameterName;
}
}
public class Person
{
[Parameter("FirstName")]
public string FirstName { get; set; }
[Parameter("LastName")]
public string LastName { get; set; }
[Parameter("EmailAddress")]
public string Email { get; set; }
}
SqlCommand command = new SqlCommand();
Person person = new Person()
{
FirstName = "John",
LastName = "Doe",
Email = "johndoe@domain.com"
};
foreach (var pi in person.GetType().GetProperties())
{
var attribute = (ParameterAttribute)pi.GetCustomAttributes(typeof(ParameterAttribute), false).FirstOrDefault();
if (attribute != null)
{
command.Parameters.AddWithValue(string.Format("@{0}", attribute.ParameterName), pi.GetValue(person, null));
}
}